Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objektorienterad programmering d2, förel. 12

Similar presentations


Presentation on theme: "Objektorienterad programmering d2, förel. 12"— Presentation transcript:

1 Objektorienterad programmering d2, förel. 12
12 Object copying DAT050, 17/18, lp 1

2 Objektorienterad programmering d2, förel. 12
Overview Object duplication – cloning In following lectures: Equality and identity relations Algebraic properties Comparison methods and objects for ordering relations Object serialization (OOA) Object streams (OOA) Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

3 Objektorienterad programmering d2, förel. 12
Well behaved classes Objects that are handled by the JVM and many standard classes should have No-arg constructor String representation (toString()) Cloning (deep copying) Equality and hashCode methods (lecture 14) Serialization (for stream i/o) (OOA) Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

4 Objektorienterad programmering d2, förel. 12
Class Object The class Object defines basic default implementations of public String toString() protected Object clone() public boolean equals(Object other) public int hashCode() They can (should!) be overridden in subclasses next! Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

5 Ex. Object model for GPS tracks
Objektorienterad programmering d2, förel. 12 Ex. Object model for GPS tracks A track consists of a list of legs ... and a course angle A leg has a start position … φ N E a length ... Man brukar lagra tidpunkter, bentider och fart också A position is made up of of a latitude ... ... and a longitude Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

6 Ex. Object model for GPS tracks
Objektorienterad programmering d2, förel. 12 Ex. Object model for GPS tracks Suppose our GPS plotter collects a track during a boat travel at the starboard side in a fairway from A to B A We want to compute a return route from B to A. In order to avoid collisions with other boats, the return route must be separated from the forward route (Ow, we go on the port side) B As a basis for creating the return route, we need a copy of the track Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

7 GPS track object configuration
Objektorienterad programmering d2, förel. 12 GPS track object configuration :Track totalLength legs Explore the gps_tracks project! :LatitudeAngle isNorth degrees minutes :Leg course length startPos :GeoPosition latitude longitude :LongitudeAngle isWest degrees minutes - How can we copy such complicated structures? Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

8 The Object.clone() method
Objektorienterad programmering d2, förel. 12 The Object.clone() method The class Object defines a default implementation of protected Object clone() It returns a shallow field-by-field copy of the calling object it does not copy referenced objects clone should be overridden: public MySubClass clone() Eftersom Object.clone har skyddad access måste man överskugga den publikt. Sen kan ev. denna ärvas vidare, eller överskuggas, allt efter behov. OBS! Vi utnyttjar kovarianta returtyper här. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

9 Objektorienterad programmering d2, förel. 12
Object.clone() LatitudeAngle la :LatitudeAngle true 57 42.349 equal but not the same LatitudeAngle laCopy = la.clone(); :LatitudeAngle true 57 42.349 Ok eftersom alla variabler har primitiv typ Inga referenser OBS! Kommentera hur det blir med strängar! A field-by-field copy of the object above la.equals(laCopy) la != laCopy Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

10 Object.clone() returns a shallow copy
Objektorienterad programmering d2, förel. 12 Object.clone() returns a shallow copy GeoPosition gp :LatitudeAngle :GeoPosition :LongitudeAngle GeoPosition gpCopy = gp.clone(); :GeoPosition referenced parts become shared Om man kopierar referenser ”field-by-field” kopieras bara addressvärden A field-by-field copy of the object above Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

11 We probably want a DEEP copy!
Objektorienterad programmering d2, förel. 12 We probably want a DEEP copy! GeoPosition gp :LatitudeAngle :GeoPosition :LongitudeAngle GeoPosition gpCopy = gp.clone(); :LatitudeAngle :GeoPosition :LongitudeAngle En djup kopiering måste göras i flera led A DEEP copy of the object above referenced parts are copied too Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

12 Recommended properties
Objektorienterad programmering d2, förel. 12 Recommended properties It is recommended that overridings of clone satisfy the following properties: For all x, each expression must evaluate to true: Weak independence x.clone() != x Equality (x.clone()).equals(x) Type identity (x.clone()).getClass() == x.getClass() Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

13 The Cloneable interface
Objektorienterad programmering d2, förel. 12 The Cloneable interface By implementing interface Cloneable a class declares that Object.clone may copy instances of the class field-by-field CloneNotSupportedException is thrown if Object.clone is called for instances not implementing Cloneable Classes which implement Cloneable should override clone Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

14 Properties of Object.clone
Objektorienterad programmering d2, förel. 12 Properties of Object.clone When Object.clone is called for an instance of a class it will return a field-by-field copy of the whole instance the copy will have the same dynamic type as the calling instance, this applies also to overridden clone methods in subclasses Notera den sista punkten! Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

15 Objektorienterad programmering d2, förel. 12
Overiding Clone public class MyClass implements Cloneable { private int x = 123; private boolean y = true; private char z = 'A'; @Override public MyClass clone() throws CloneNotSupportedException return (MyClass)super.clone(); } ... MyClass x = new MyClass(); MyClass copy = x.clone(); Object.clone copies x,y,z It returns an object having static type Object, but dynamic type MyClass - so the type cast will be OK! Använd ALDRIG new i clone! Det fungerar inte vid arv. ”implements Cloneable” behöver ej upprepas i subklasser no need for a cast here Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

16 Objektorienterad programmering d2, förel. 12
Overiding Clone (2) public class MyClass // implements Cloneable { private int x = 123; private boolean y = true; private char z = 'A'; @Override public MyClass clone() throws CloneNotSupportedException return (MyClass)super.clone(); } ... MyClass cc = new MyClass(); MyClass copy = cc.clone(); Object.clone throws CloneNotSupportedException Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

17 Objektorienterad programmering d2, förel. 12
Overiding Clone (3) public class MyClass implements Cloneable { private int x = 123; private boolean y = true; private char z = 'A'; @Override public MyClass clone() { try { return (MyClass)super.clone(); } catch ( CloneNotSupportedException e) { throw new InternalError(); Om klassen ärver från Object och man får CloneNotSupportedException är något helt fel i JVM:en. Kasta InternalError! Detta är ett sätt ... If Object.clone throws CloneNotSupportedException, something is seriously wrong in the JVM Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

18 Objektorienterad programmering d2, förel. 12
Overiding Clone (4) public class NoCopy { private int x = 123; private boolean y = true; private char z = 'A'; @Override public NoCopy clone() throws CloneNotSupportedException throw new CloneNotSupportedException(); } ... NoCopy nc = new NoCopy(); nc.clone(); Use this scheme if instances of a class may not be cloned throws CloneNotSupportedException Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

19 Deep and shallow copying
Objektorienterad programmering d2, förel. 12 Deep and shallow copying Suppose we want a copy of the entire object graph referenced by v1 :C1 :C2 :C2 :C2 v1 :C3 :C3 :C3 Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

20 The first attempt - Shallow copy
Objektorienterad programmering d2, förel. 12 The first attempt - Shallow copy A simple assignment of an object reference is in most cases inadequate - some objects will be shared v2 = v1; :C1 :C2 :C2 :C2 v1 :C3 :C3 :C3 v2 Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

21 Objektorienterad programmering d2, förel. 12
The second attempt v2 = v1.clone(); C1.clone() calls super.clone() (as in previous slides) - the list is shared :C1 v1 :C1 v2 :C2 :C2 :C2 :C3 :C3 :C3 Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

22 Objektorienterad programmering d2, förel. 12
The third attempt Inadequately overridden clone in C1 copies the list but not the list elements - the list elements are shared v2 = v1.clone(); :C1 v1 :C1 v2 :C2 :C2 :C2 Titta på kloning av listor i API:t :C3 :C3 :C3 Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

23 Objektorienterad programmering d2, förel. 12
The fourth attempt Overridden clone in C1 copies the list and the list elements correctly - but C2 does just a shallow copy! v2 = v1.clone(); :C1 :C2 :C2 :C2 v1 :C3 :C3 :C3 v2 :C2 :C2 :C2 :C1 Här har C1 uppfyllt sitt kontrakt. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

24 Objektorienterad programmering d2, förel. 12
The final version Finally, also C2 overrides clone v2 = v1.clone(); :C1 :C2 :C2 :C2 v1 :C3 :C3 :C3 - nothing left to share :C3 :C3 :C3 v2 :C1 :C2 :C2 :C2 Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

25 Cloning and inheritance
Objektorienterad programmering d2, förel. 12 Cloning and inheritance Redefined clone methods in subclasses calls super.clone() class Sub extends Base { @Override public Sub clone() { Sub result = (Sub)super.clone(); ... return result; } Sub Base Add copies of sub class specific fields to result Om super.clone är en överskuggning av Object.clone så vet vi att returvärdet har dynamisk typ Sub. Alltså är typomvandligen ok. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

26 Copying cyclic structures
Objektorienterad programmering d2, förel. 12 Copying cyclic structures In cyclic structures and structures where parts are shared, care must be taken to preserve the sharing patterns of the original in the copy. Copy Original Wrong! Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

27 Objektorienterad programmering d2, förel. 12
Ex. Angle clone method public class Angle implements Cloneable { private int degrees; private float minutes; ... @Override public Angle clone() { try { return (Angle)super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); Explore the gps_tracks project! Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

28 Ex. LatitudeAngle clone method
Objektorienterad programmering d2, förel. 12 Ex. LatitudeAngle clone method public class LatitudeAngle extends Angle { private boolean isNorth; ... @Override public LatitudeAngle clone() { return (LatitudeAngle)super.clone(); } // LongitudeAngle similar Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

29 Ex. GeoPosition clone method
Objektorienterad programmering d2, förel. 12 Ex. GeoPosition clone method public class GeoPosition implements Cloneable { private LatitudeAngle latitude; private LongitudeAngle longitude; ... @Override public GeoPosition clone() { GeoPosition copy = null; try { copy = (GeoPosition)super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); copy.latitude = latitude.clone(); copy.longitude = longitude.clone(); return copy; Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

30 Objektorienterad programmering d2, förel. 12
Ex. Leg clone method public class Leg implements Cloneable { private GeoPosition startPos; private int course; private float length; ... @Override public Leg clone() { Leg copy = null; try { copy = (Leg)super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); copy.startPos = startPos.clone(); return copy; Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

31 Objektorienterad programmering d2, förel. 12
Ex. Track clone method public class Track implements Cloneable { private float totalLength; private ArrayList<Leg> legs; ... @Override @SuppressWarnings("unchecked") public Track clone() { Track copy = null; try { copy = (Track)super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); copy.legs = (ArrayList<Leg>)legs.clone(); for ( int i = 0; i < legs.size(); i++ ) copy.legs.set(i,legs.get(i).clone()); return copy; Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

32 String, clone and equality
Objektorienterad programmering d2, förel. 12 String, clone and equality Java strings are immutable and can therefore be stored in shared memory, so there is no need to copy strings String does not override Object.clone The following code creates just one String object – so s1 == s2 is true String s1 = ”abc”; String s2 = ”abc”; s1 s2 ’a’ ’b’ ’c’ Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

33 String, clone and equality
Objektorienterad programmering d2, förel. 12 String, clone and equality String has a constructor taking a String argument. The following code creates two distinct String objects, but they will share the same character array so s1 == s2 is false but s1.equals(s2) is true String s1 = new String(”abc”); String s2 = new String(”abc”); Always use the equals method when testing string equality! s1 s2 ’a’ ’b’ ’c’ Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1

34 Objektorienterad programmering d2, förel. 12
References Angelika Langer, Das Kopieren von Objekten in Java, (In Deutsch) ? Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1


Download ppt "Objektorienterad programmering d2, förel. 12"

Similar presentations


Ads by Google