Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,

Similar presentations


Presentation on theme: "Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,"— Presentation transcript:

1 Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
To object or not… David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Revised: 28/11/2017 ~ more tweaks! Object vs. reference… previous: 29/11/2016 ~ minor tweaks! 25/11/2012, 7/12/2010

2 IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

3 Object vs. Reference In the “real” world …so too in Java! Derya David
CS101 instructor In real world we distinguish between an object itself & references to it (ways of referring to it), of which there may be many. David & Derya are two different individuals. David & CS101 instructor are not. Only one David (thank goodness?), but if cloned then would want to say the copy is a different individual (object) having identical properties. May think cloning is somewhat irrelevant, but far from it. In today’s world, “clones” are everywhere! Not yet in the form of people, but of (manufactured) objects! e.g. bottles of water, pens, cellphones, etc., etc. Each is an individual object, but one that shares all relevant properties when created. Java must (& does) match our “real world” intuitions. But need to change the mental model of memory we have been using (for primitive types.) Demonstrate how putting david’s data on paper in location “david”, and then the same data on a paper in another location “cs101Instructor” fails to conform to our intuitions (about how reality functions) during updates (e.g. to age) So, change mental model of memory to accommodate… now rather than putting paper into box (memory location) data is written (on paper) on a balloon that floats in mid-air & is attached to the box with a piece of string the same (paper) balloon can be held by strings coming from several boxes. Derya’s dad David2

4 cs101Instructor {Person}
Object vs. Reference In the Java world…? david 23 david 22 david 22 derya 18 derya 19 david {Person} cs101Instructor {Person} derya {Person} Note: slide shows direct access to properties, which is BAD but, same applies when using methods! So, our abstract picture in Java now looks like this. This distinction between object & reference has two important implications: There are two notions of what “same” means and there are two notions of what “copy” means We will look at each of these in turn…. david.age++; derya.age++; Sys…( david.age ); Sys…( cs101Instructor.age ); oops!

5 cs101Instructor {Person}
Object vs. Reference In the Java world need to revise our mental model! David Derya david 22 david 23 derya 19 derya 18 david {Person} derya {Person} So, our abstract picture in Java now looks like this. This distinction between object & reference has two important implications: There are two notions of what “same” means and there are two notions of what “copy” means We will look at each of these in turn…. cs101Instructor {Person} deryasDad {Person} David’s clone david2 {Person} david 22

6 Two Implications Separating object & reference has for Equality
& for Copying

7 For Equality ~Same or Different? (1)
Comparing objects myQCd {CD} Title B.R. Artist Queen Date 1976 Length 3:50 myCd {CD} Title Best of Artist Genesis Date 1983 Length 2:40 yourCd {CD} if ( myCd == yourCd) System.out.println( “Same”); else System.out.println( “Different”); Both these report different! Doesn’t exactly correspond to our intuitions. Sure they are different objects, but in another sense they are the same, they are copies of the same CD. “==“ is comparing references, not the object properties. “==“ says whether the references refer to the same individual object or to two distinct objects. So, only “myCd == myQCd” would give true. Title B.R. Artist Queen Date 1976 Length 3:50 yourQCd {CD} if ( myCd == yourQCd) System.out.println( “Same”); else System.out.println( “Different”);

8 For Equality ~Same or Different? (2)
Define an “equals” method myQCd {CD} Title B.R. Artist Queen Date 1976 Length 3:50 myCd {CD} Title Best of Artist Genesis Date 1983 Length 2:40 yourCd {CD} if ( myCd.equals( yourCd) ) System.out.println( “Same”); else System.out.println( “Different”); Can write an equals method in CD class that compares CD’s by content, not reference. These should report different & same in accord with our intuitions. And, of course, “myCd.equals( myCd)” would give true! Note: for reasons we will come to later, the method signature should be “boolean equals( Object o)” rather than “boolean equals( CD aCd)” so need to check class is correct too, i.e. comparing same sorts of objects! Write such a method. Note: you could name the method anything you want, “equals” is the convention Java uses… so follow it! Title B.R. Artist Queen Date 1976 Length 3:50 yourQCd {CD} if ( myCd.equals( yourQCd) ) System.out.println( “Same”); else System.out.println( “Different”);

9 For Copying in primitive vs. Object types… Different Same! int i, j;
j = i; i++; Sys… ( i, j); Person me, x; me = new Person( …); x = me; me.setComments( “nice!”); Sys… ( me.getComments() + x.getComments(), ); Demonstrating that copying has different semantics for primitive and object type data. You should be able to see the parallel in the code segments. Note that “j = i;” and “x = me” look exactly the same! But the difference in kind (primitive vs. object) means they have different semantics. (obviously resulting from the object reference distinction) Different but j = i: looks-like x = me; Same!

10 For Copying ~Copy vs. Clone
Title B.R. Artist Queen Date 1976 Length 3:50 Title B.R. Artist Queen Date 1976 Length 3:50 myCd {CD} yourQCd {CD} Copying merely copies the reference, making the copy refer to the same object. Clone involves creating an entirely new object and copying all the properties of the first into it. Write such a method. Note: This is crucial to parameter passing to and returning results from methods when using objects. Note: Java automatically provides a clone method for all objects, BUT be careful, it performs a “shallow” copy, which is fine for primitive types, but not necessarily for embedded objects (which end up shared by both the original and clone objects!) Note: doing clone() properly is a problem since it requires implementing clonable & handling exceptions!) Use copy constructors as an alternative. For example, yourQCd = new CD( myCd); favouriteCd {CD} Alternatively, use “copy constructor” yourQCd = new CD( myCd ); favouriteCd = myCd; yourQCd = myCd.clone(); Copies reference Copies object

11 Parameter Passing (1) Primitive types… a b i 5 6 5 6 main xyz main
public int xyz( int i) { i++; return i; } 5 6 5 6 The copy-clone distinction has important consequences for parameter passing… Note: This, and the following examples, actually assume static methods, but this is irrelevant. Passing the actual to formal parameters entails “copying” them (this is a primitive type copy). Same for passing the result back… it involves “copying” the value (again a primitive type copy). NOTICE – changing formal parameter in method DOES NOT affect associated actual parameter variable. main int a, b; a = 5; b = xyz( a); Sys… ( a, b);

12 Parameter Passing (2) Object types… a b x main xyz main
David “” public Person xyz( Person x) { x.setComments(“Nice); return x; } Nice a b main x xyz NOTICE – changing the properties of the object referred to by the formal parameter in the method DOES change the properties of the corresponding (actual parameter’s) object in the main method. In effect, technically speaking, objects are “passed by reference” in Java (while primitive types are “passed by value”). main Person a, b; a = new Person( “David” …); b = xyz( a); Sys… ( a.getComments() + b.getComments() );

13 Parameter Passing (3) Object types… a b x main xyz main
David “” Derya “” public Person xyz( Person x) { x = new Person( “Derya” …); x.setComments(“Nice); return x; } Nice a b main x xyz NOTICE – changing the reference of the formal parameter in the method DOES NOT change the corresponding actual parameter’s reference in the main method. main Person a, b; a = new Person( “David” …); b = xyz( a); Sys… ( a.getComments() + b.getComments() );

14 Special methods, garbage collection & null references
Extra Bits…

15 All Objects… automatically have BUT boolean equals( Object)
Object clone() String toString() int hashCode() BUT they may not do what you would like/expect, so implement yourself! Code using these methods will compile & run even if your class does not define them! & hashCode, but perhaps ignore for now! Note: toString automatically called when you ask Java to print an Object. Normally it won’t print anything very pretty, so you write it to return a nice neat version of your objects properties, ready to be printed. equals() defaults to “==“ clone() defaults to “shallow copy” toString() defaults to Note: see documentation for Object class for real details… in general, hashCode’s must be “equal for equal objects” hence changing “equals” really requires implementing “hashCode”

16 Lost objects & null Java collects its garbage! aCd = null;
Title B.R. Artist Queen Date 1976 Length 3:50 Title Best of Artist Genesis Date 1983 Length 2:40 yourCd {CD} What happens when “myCd = yourCd;” is executed? Variable only refers to one object at a time. So my Queen CD is lost… the string is cut and the balloon floats off into the atmosphere… Objects having no references to them cannot be used! They are effectively garbage (rubbish/trash to be “disposed” of) Java automatically collects such garbage allowing the space to be reused/recycled for other objects (thus ensuring that “memory leaks” do not clog up and eventually stop the system). “null” is a special value that can only be applied to references. Can compare references to null e.g. if ( aCd == null) or if ( myCd != null) Cannot compare references using <, >, <=, >= (or add, subtract or multiply them!) Note: Attempting to access the properties or methods of an object that doesn’t exist because the reference is null, results in a “nullPointerException”. It should be nullReferenceException or some such. The word pointer is the old terminology for reference! myCd {CD} aCd {CD} aCd = null; myCd = yourCd;

17 Static vs. Instance

18 Static vs. instance Variables
“count” as an instance variable -- each instance (object) has count variable name age salary comments Person c.count++; a.count = 3; count instance Could (1) have int count variable outside class-but difficult to maintain, (2) associate with class, but can’t be instance variable-why not? (3) make static variable in class… only one copy in class, not instances. Here, count is initialised to zero when declared(!), then incremented in constructor. Each instance of the class, i.e. each individual object, has its own values for each instance variable. But there is only ever one copy of a static variable (also called a class variable.) Static data accessible via classname.variablename (and object.variablename) Instance data only accessible via object.variablename syntax. Static data can be accessed even if there are no instances of the class. Same goes for static methods, e.g. a getCount() method here or the main method! Note: static methods can only refer to static data (and data defined locally in method.) Why? Static data used for constant definitions (outside method but in class) –never changes so only need one copy! for singletons (classes which allow one and only one object to be created.) David “Quiet” Derya “Nice” Gunes “Sunny” Ayse “Happy” 3 2 a b c d

19 Static vs. instance Variables
“count” as a static variable -- only one count variable, associated with class name age salary comments Person also known as “class variables” static count 1 4 2 3 initialise count to zero, then increment it in constructor instance Could (1) have int count variable outside class-but difficult to maintain, (2) associate with class, but can’t be instance variable-why not? (3) make static variable in class… only one copy in class, not instances. Here, count is initialised to zero when declared(!), then incremented in constructor. Each instance of the class, i.e. each individual object, has its own values for each instance variable. But there is only ever one copy of a static variable (also called a class variable.) Static data accessible via classname.variablename (and object.variablename) Instance data only accessible via object.variablename syntax. Static data can be accessed even if there are no instances of the class. Same goes for static methods, e.g. a getCount() method here or the main method! Note: static methods can only refer to static data (and data defined locally in method.) Why? Static data used for constant definitions (outside method but in class) –never changes so only need one copy! for singletons (classes which allow one and only one object to be created.) David “Quiet” Derya “Nice” Gunes “Sunny” Ayse “Happy” a b c d

20 Misc: Can combine, so static “nextID” gives next value to be assigned to instance variable “personID”. Constants often defined as static hence saving space public static final double PI = 3.142; public static final String COMPANY = “Bilkent University”;

21 Static vs. instance Methods
Classes can have both static & instance methods. Static methods useful when accessing static variables public static int getCount() object state is not needed public static int getAge( day, month, year) Static methods cannot access instance variables or methods Instance methods can access static & instance, variables & methods Why are static methods not allowed to access instance variables (or instance methods!)

22 Singletons (design pattern)
Problem: Ensure only a single instance of a class is created. (for database or network connections, etc.) Solution: Combine static variable, private constructor & static method! public class SingletonClass { private static SingletonClass singletonObj = new SingletonClass(); private SingletonClass() { } public static SingletonClass getInstance() { return singletonObj; Other uses include print spoolers… Note: can also do lazy creation of object by only creating it if property is null. A number of further considerations may apply in practice, e.g. need to override clone method, make synchronized if multiple threads, etc.

23 Can also mention “this” if not already done so…
generally introduce as way to resolve parameter/property names in constructors. And don’t forget about the sorts of relationships between objects, i.e. is_a, has_a and uses. One day, introduce UML notations! Now… practice makes perfect (or at least helps you on the way!)


Download ppt "Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,"

Similar presentations


Ads by Google