Download presentation
Presentation is loading. Please wait.
Published bySteffen Christophersen Modified over 5 years ago
1
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
To object or to reference… David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Revised: 11/12/2018 ~ removed static vs. instance stuff from end and put in separate file! (still need to tidy some of the animations etc. for null / garbage collection, etc.) previous: 30/11/2017 ~ some more tweaks, garbage & null separated, ~~more in progress! 28/11/2017 ~ more tweaks! Object vs. reference… 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} Revised mental model… - info still on paper, - but now paper stuck to balloon, - and connected to a memory location/box by a piece of string! + restrictions: balloon can be attached by any number of strings but each box can hold only one piece of string! (note box may hold no string at all). 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 Implications for
The distinction btw object & reference results in two different notions of equality & two of copying! This has further implications for parameter passing to methods… Conventional distinction is between pass by value & pass by reference The former is “input only” (changes made to the formal param inside the method do not affect the corresponding actual param) The latter commonly allows both the reference & the object to be changed, however, Java passes the ref by value & allows only the objects properties to be changed! Thus object param’s in Java can be used for outputs from the method too! Parameter passing
12
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);
13
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() );
14
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() );
15
Special methods, garbage collection & null references
Extra Bits…
16
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! 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” hashCode - ignore for now - except to note that + technically changing equals requires changing hasCode + toString is ClassName + + hashCodeInHexaDecimal
17
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;
18
Consider splitting here..?
i.e. make static vs instance as part3
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.