Objektorienterad programmering d2, förel. 12

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

ACM/JETT Workshop - August 4-5, Classes, Objects, Equality and Cloning.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Effective Java, Chapter 3: Methods Common to All Objects.
Effective Java, Chapter 3: Methods Common to All Objects Paul Ammann.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Tirgul 1 Today’s subjects: –First programming exercise. –Java reminder & completions : reference data types, cloning, inner classes, packages. –Short reminder.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
Mutable, Immutable, and Cloneable Objects Chapter 15.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Implications of Inheritance COMP204, Bernhard Pfahringer.
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Advanced Programming Rabie A. Ramadan vpro/ Lecture 4.
Java Implementation: Part 4 Software Construction Lecture 9.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Java Type System and Object Model Horstmann ch , 7.7.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Classes Revisited Chapter 8.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
C11, Implications of Inheritance
Objektorienterad programmering d2, förel. 8
Chapter 7: Cloning and RTTI
Polymorphism 2nd Lecture
Object-oriented Programming in Java
03/10/14 Inheritance-2.
CSC 205 Java Programming II
10 More about inheritance
Chapter 8 Classes and Objects
Programming Language Concepts (CIS 635)
CIS3023: Programming Fundamentals for CIS Majors II
Computer Science II Exam 1 Review.
CSE 331 Cloning objects slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Java Programming Language
Polymorphism and access control
CSE 1030: Data Structure Mark Shtern.
Sampath Kumar S Assistant Professor, SECE
Generic Classes and Methods
Effective Java, Chapter 3, 3rd Edition: Methods Common to All Objects
Objektorienterad programmering d2, förel. 8
Interfaces.
Java Programming Language
Chapter 8 Class Inheritance and Interfaces
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
CMPE212 – Reminders Assignment 2 due next Friday.
CS 240 – Advanced Programming Concepts
Presentation transcript:

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

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

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

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

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 57 36.071 E 11 27.980 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

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

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

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

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

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

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

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

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

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

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! OBS @Override 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Objektorienterad programmering d2, förel. 12 References Angelika Langer, Das Kopieren von Objekten in Java, http://www.angelikalanger.com/Articles/EffectiveJava/05.Clone-Part1/05.Clone-Part1.html http://www.angelikalanger.com/Articles/EffectiveJava/06.Clone-Part2/06.Clone-Part2.html http://www.angelikalanger.com/Articles/EffectiveJava/07.Clone-Part3/07.Clone-Part3.html (In Deutsch) ? Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 1