C OMP 401: C ONSTRUCTORS AND P OINTERS Instructor: Prasun Dewan (FB 150,

Slides:



Advertisements
Similar presentations
Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
Advertisements

F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Today Quiz solutions are posted on the Grading page. Assignment 1 due today, 7pm. Arrays as Pointers, Cont. Aliasing & Passing by Reference null Winter.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
C OMP 110 S TATE Instructor: Jason Carter. 2 O UTLINE Instance Variables Procedures Properties Print Statements Println vs. Print Overloading.
C OMP 110 T YPES Instructor: Jason Carter. 2 O BJECTS VS. P RIMITIVE T YPES Instances of classes and interfaces are objects All other values are primitives.
C OMP 401 M EMORY R EPRESENTATION OF P RIMITIVE V ALUES AND O BJECTS Instructor: Prasun Dewan.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
C OMP 401 C LASS S TATE Instructor: Prasun Dewan.
C OMP 110 C ONDITIONALS Instructor: Jason Carter.
C OMP 110 S TYLE Instructor: Jason Carter. 2 I NTERFACES AND M ORE S TYLE Define contracts between our users and implementers Optional – they may not.
C OMP 401 O BJECTS Instructor: Prasun Dewan 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
C OMP 110 L OAN C ASE S TUDY Instructor: Jason Carter.
C OMP 110 O BJECTS Instructor: Jason Carter. 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
By - Qiong Han. DON’T FALL BEHIND IN READING Submission Instruction Everyone needs to submit the printed HARD- COPY of the codes and the grading sheets.
Midterm Exam 75 points 1 min per point Allocate time proportionate to points Closed book Chapters 1-5 (except char) PDF/PS with index and corrections coming.
Object-based Programming Intuitive explanation Using objects to read input Creating objects Style rules.
Program Style Identifier Names Comments Named Constants Avoiding Code Repetition Giving Least Privilege Efficiency Interfaces.
Comp 14 (3) By Stephan Sherman Office hours, W, 3:00-3:50pm.
Object-based Programming Intuitive explanation Using objects to read input Creating objects Style rules.
Class Variables & Methods More on dependencies Representation and representation errors Primitive vs. Object Properties Class Variables/Methods Primitive.
Chapter 3 Classes and Methods. 2 Knowledge Goals Appreciate the difference between a class in the abstract sense and a class as a Java construct Know.
Programmer-Defined Types Object Types as Programmer-defined Types Two-way Dependencies Representation Errors Primitive Vs Object Properties Constructors.
Fundamental Programming Structures in Java: Strings.
Object Types Primitive types Primitive Vs Object Types Types Classes ABMISpreadsheet AnotherBMISpreadsheet Interfaces BMISpreadsheet Loan Stringdoubleint.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Class Variables & Methods More on dependencies Representation and representation errors Primitive vs. Object Properties Class Variables/Methods Primitive.
State Instance Variables Procedures Properties Print Statements Println Vs Print Overloading J++
Bicycle Car Types pedal() pushAccelerator(). Stringdoubleint Programming Language Types “three”“four” = 7 = “threefour” + + / = 0 / = 0.75.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
C OMP 401 C LASS S TATE Instructor: Prasun Dewan.
1 Chapter 10 Object-Oriented Thinking. 2 Class Abstraction and Encapsulation Class abstraction means to separate class implementation details from the.
C OMP 110/401 C OMPOSITE A NNOTATIONS Instructor: Prasun Dewan.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
C OMP 110 T YPES Instructor: Prasun Dewan 2 P REREQUISITES Interfaces.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
C OMP 110/401 D OCUMENTATION : C OMMENTS Instructor: Prasun Dewan.
C OMP 110/401 E NCAPSULATION AND L EAST P RIVILEGE Instructor: Prasun Dewan.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Cs2220: Engineering Software Class 3: Java Semantics Fall 2010 University of Virginia David Evans.
Recitation 8 User Defined Classes Part 2. Class vs. Instance methods Compare the Math and String class methods that we have used: – Math.pow(2,3); – str.charAt(4);
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
A DVANCED P ROGRAMMING C HAPTER 4: I NTRODUCTION TO I NTRODUCTION TO C LASSES, O BJECTS, M ETHODS AND STRINGS Dr Shahriar Bijani Winter 2016.
C OMP 401 P RACTICAL A PPLICATIONS OF MVC AND O BSERVER : P ROPERTY N OTIFICATION Instructor: Prasun Dewan.
C OMP 401 E XCEPTIONS -R EMAINDER Instructor: Prasun Dewan.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Declaring console static and global import java.util.*; public class Test { static Scanner console = new Scanner (System.in); public static void main(String[]
C OMP 110/401 D OCUMENTATION : A NNOTATIONS Instructor: Prasun Dewan.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Java: Base Types All information has a type or class designation
Java: Base Types All information has a type or class designation
AKA the birth, life, and death of variables.
March 29th Odds & Ends CS 239.
Recitation 4 September 16, 2011.
Review Session Biggest discrepancy questions
Recitation 3 September 9, 2011 Wade Gobel.
Object-Oriented Java Programming
Classes and Objects Object Creation
Corresponds with Chapter 5
CMSC 202 Constructors Version 9/10.
Presentation transcript:

C OMP 401: C ONSTRUCTORS AND P OINTERS Instructor: Prasun Dewan (FB 150,

2 ALoopingFactorialSpreadsheet factorial1 = new ALoopingFactorialSpreadsheet (); ALoopingFactorialSpreadsheet factorial = new ALoopingFactorialSpreadsheet (); ALoopingFactorialSpreadsheet factorial = new ALoopingFactorialSpreadsheet (); factorial1.setNumber(2); factorial2.setNumber(2); A C LASS (W ITH P ROPERTIES ) public class ALoopingFactorialSpreadsheet { int number; long factorial; public int getNumber() { return number; } public void setNumber(int newVal) { number = newVal ; factorial = Factorials.loopingFactorial(number); } public long getFactorial() { return factorial; }

3 A NOTHER C LASS WITH P ROPERTIES public class ABMISpreadsheet { double height; double weight; public double getWeight() { return weight; } public void setWeight(double newWeight) { weight = newWeight; } public double getHeight() { return height; } public void setHeight(double newHeight) { height = newHeight; } public double getBMI() { return weight/(height*height); } Height Weight BMI

4 public class BMISpreadsheetUser { public static void main(String[] args) { ABMISpreadsheet bmiSpreadsheet = new ABMISpreadsheet(); bmiSpreadsheet.setHeight(1.77); bmiSpreadsheet.setWeight(75); System.out.println(bmi.getBMI()); } U SING BMIS PREADSHEET

5 ABMIS PREADSHEET AND C ONSTRUCTOR public class ABMISpreadsheet { double height; double weight; public ABMISpreadsheet(double theInitialHeight, double theInitialWeight) { setHeight(theInitialHeight); setWeight(theInitialWeight); } public double getWeight() { return weight; } public void setWeight(double newWeight) { weight = newWeight; } public double getHeight() { return height; } public void setHeight(double newHeight) { height = newHeight; } public double getBMI() { return weight/(height*height); } Constructor name must be the name of the class Constructor name is also the type of object returned ABMISpreadsheet aBMISpreadsheet = new ABMISpreadsheet( 1.77, 75.0); Constructors do not appear in interfaces

6 E VERY C LASS HAS A C ONSTRUCTOR public class ABMISpreadsheet { double height; double weight; public double getWeight() { return weight; } public void setWeight(double newWeight) { weight = newWeight; } public double getHeight() { return height; } public void setHeight(double newHeight) { height = newHeight; } public double getBMI() { return weight/(height*height); }

7 public class ABMISpreadsheet { double height; double weight; public ABMISpreadsheet() { } public double getWeight() { return weight; } public void setWeight(double newWeight) { weight = newWeight; } public double getHeight() { return height; } public void setHeight(double newHeight) { height = newHeight; } public double getBMI() { return weight/(height*height); } E QUIVALENT C LASS C REATED BY J AVA If Programmer Specifies no Constructor, Java inserts a null constructor Inserted in Object Code not in Source Code

8 A C LASS C AN H AVE M ULTIPLE C ONSTRUCTORS public class ABMISpreadsheet { double height; double weight; public ABMISpreadsheet() { } public ABMISpreadsheet(double theInitialHeight, double theInitialWeight) { setHeight(theInitialHeight); setWeight(theInitialWeight); } public double getWeight() { return weight; } public void setWeight(double newWeight) { weight = newWeight; } public double getHeight() { return height; } public void setHeight(double newHeight) { height = newHeight; } public double getBMI() { return weight/(height*height); } Overloaded Constructor Two methods with the same name are overloaded The lists of parameter types must be different The method headers must be different ignoring the return type

9 A C LASS C AN H AVE M ULTIPLE C ONSTRUCTORS (R EVIEW ) public class ABMISpreadsheet { double height; double weight; public ABMISpreadsheet() { } public ABMISpreadsheet(double theInitialHeight, double theInitialWeight) { setHeight(theInitialHeight); setWeight(theInitialWeight); } public double getWeight() { return weight; } public void setWeight(double newWeight) { weight = newWeight; } public double getHeight() { return height; } public void setHeight(double newHeight) { height = newHeight; } public double getBMI() { return weight/(height*height); } Overloaded Constructor Two methods with the same name are overloaded The lists of parameter types must be different The method headers must be different ignoring the return type

10 public class BMISpreadsheetUser { public static void main(String[] args) { ABMISpreadsheet bmiSpreadsheet = new ABMISpreadsheet(); bmiSpreadsheet.setHeight(1.77); bmiSpreadsheet.setWeight(75); //equivalent computation bmiSpreadsheet = new ABMISpreadsheet(1.77, 75); } U SING O VERLOADED C ONSTRUCTORS Using Overloaded Constructor

11 A RE (P ROGRAMMER -D EFINED ) C ONSTRUCTORS EVER A BSOLUTELY N ECESSARY ? ABMISpreadsheet aBMISpreadsheet = new ABMISpreadsheet(); aBMISpreadsheet.setHeight(1.77); aBMISpreadsheet.setWeight(75.0); Programmer can initialize state after instantiation (requires a bit more work but possible in this case) ABMISpreadsheet aBMISpreadsheet = new ABMISpreadsheet( 1.77, 75.0); Always possible? Can use the full functionality of class without programmer- defined constructor Some part of the exported state (e.g. height) may be readonly

12 I MMUTABLE O BJECTS String s = new String("hello"); String is immutable. An immutable object cannot be changed after initialization. An immutable object with state must have one or more programmer- defined constructors to initialize the state String s = “hello";

13 C HANGING VARIABLE VS. O BJECT String s = "hello"; String hello = s; s += " world"; System.out.println(s == hello); Assigns to s a new String object Does not change the original String StringBuffer s = new StringBuffer("hello"); StringBuffer hello = s; s.append(" world"); System.out.println(s == hello); Does not reassign s Changes the object to which s points Reassigning a new object less efficient false true

14 public class BMISpreadsheetUser { public static void main(String[] args) { ABMISpreadsheet bmiSpreadsheet = new ABMISpreadsheet(); bmiSpreadsheet.setHeight(1.77); bmiSpreadsheet.setWeight(75); double computedBMI = bmiSpreadsheet.getBMI(); System.out.println(computedBMI ); } O BJECTS VS. P RIMITIVES Primitive Variable Object Variable Object Value Primitive Value

15 P RIMITIVES VS. O BJECT V ARIABLES Primitive Variables double computedBMI = 22.5; double weight = 75.8; Object Variables ABMISpreadsheet bmiSpreadsheet = new ABMISpreadsheet(1.77, 75) ; variablesmemory computedBMI weight bmiSpreadsheet 1.77height weight75 52

16 P RIMITIVES VS. O BJECTS S TORAGE variablesmemoryaddresses 1.77height weight0 0height weight0 bmiSpreadsheet264 bmiSpreadsheet Primitive Variable Object Variable Primitive Value Object Value (Address) ABMISpreadsheet bmiSpreadsheet1 = new ABMISpreadsheet(); ABMISpreadsheet bmiSpreadsheet2 = new ABMISpreadsheet(); bmiSpreadsheet1.setHeight(1.77); bmiSpreadsheet2 = bmiSpreadsheet1;

17 public class BMISpreadsheetUser { public static void main(String[] args) { ABMISpreadsheet bmiSpreadsheet; bmiSpreadsheet.setHeight(1.77); bmiSpreadsheet.setWeight(75); double computedBMI; System.out.println(computedBMI ); } U NINITIALIZED P RIMITIVE VS. O BJECT V ARIABLES Uninitialized Primitive Variable Uninitialized Object Variable

18 D EFAULT V ALUES FOR V ARIABLES Primitive Variables double computedBMI; double weight; Object Variables ABMISpreadsheet bmiSpreadsheet; variablesmemory 0.0 null computedBMI weight bmiSpreadsheet Legal double values Illegal ABMISpreadsheet value

19 I NVOKING M ETHODS ON NULL bmiSpreadsheet.getBMI() null pointer exception Exception is an unexpected event (error) Guilty method will be terminated and exception reported Will see other exceptions later

20 E XTRA

21 W HY I MMUTABLE S TRING ? Easier to implement (do not have to address insertions) Immutable objects make it is easier to implement correct programs with threads and hashtables StringBuffer supports mutable strings String s1 = "hello world"; String s2 = "hello world"; System.out.println(s1 == s2); true Allows literals (String constants) to share memory location

22 W HY I MMUTABLE S TRING ? StringBuffer supports mutable strings String s1 = new String ("hello world"); String s2 = new String ("hello world"); System.out.println(s1 == s2); false New String Allocated