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.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Lecture 5: Interfaces.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Identity and Equality Based on material by Michael Ernst, University of Washington.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Effective Java, Chapter 3: Methods Common to All Objects.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Effective Java, Chapter 3: Methods Common to All Objects Paul Ammann.
== equals ? CSE 331 SOFTWARE DESIGN & IMPLEMENTATION EQUALITY Autumn 2011.
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.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
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.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
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.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Equality CSE 331 University of Washington. Object equality A simple idea - we have intuitions about equality: - Two objects are equal if they have the.
Java Implementation: Part 3 Software Construction Lecture 8.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Implications of Inheritance COMP204, Bernhard Pfahringer.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Implications of Inheritance COMP206, Geoff Holmes and Bernhard Pfahringer.
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 ==, equals(), and all that (Slides by David Notkin and Mike Ernst) 1.
Does not implement clone() method! public class Bar { … public Object clone() { … } Does not implement Cloneable interface!
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Java Implementation: Part 4 Software Construction Lecture 9.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
Classes Dwight Deugo Nesa Matic
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,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
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.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Classes Revisited Chapter 8.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
1 CSE 331 The Object class; Object equality and the equals method slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
C11, Implications of Inheritance
Modern Programming Tools And Techniques-I
Polymorphism 2nd Lecture
Lecture 12 Inheritance.
Object-oriented Programming in Java
CSC 205 Java Programming II
Chapter 8 Classes and Objects
CSE 331 Software Design and Implementation
CSE 331 Cloning objects slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Testing, cont., Equality and Identity
null, true, and false are also reserved.
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Sampath Kumar S Assistant Professor, SECE
Effective Java, Chapter 3, 3rd Edition: Methods Common to All Objects
Lecture 25: Inheritance and Polymorphism
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Review for Midterm 3.
CS 240 – Advanced Programming Concepts
Presentation transcript:

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 class doesn’t implement Cloneable, a CloneNotSupportedException is thrown x.clone() != x; –Modification to X no longer affect X.clone( ) x.clone.getClass() == x.getClass(); Usually, x.equals(x.clone()) == true; –However, this is not a requirement

2 Why Override clone() ? First, Object’s clone is a protected method –Its visibility can be increased: Sometimes a deeper copy of a field is required public class X implements Cloneable { public Object clone () throws CloneNotSupportedException { return super.clone(); } public class X implements Cloneable { private A a; public Object clone () throws CloneNotSupportedException { X x = (X)super.clone(); if(a != null) x.a = (A)a.clone(); return x; }

3 Pitfalls in Overriding clone() Implementing clone() using a constructor public class X implements Cloneable { public Object clone () throws CloneNotSupportedException { return new X(); } public class Y extends X { //use clone from X } Clone returns wrong type! public class Y extends X { public Object clone () throws CloneNotSupportedException { Y y = (Y)super.clone(); … } Exception!

4 Pitfalls in clone() - Cont Using Constructors to copy subobjects –if field a refers to an object of a subclass of A, the cloned object will be different from the original public class X implements Cloneable { private A a; public Object clone () throws CloneNotSupportedException { X x = (X)super.clone(); if(a != null) x.a = new A(); return x; }

5 equals(), hashCode() Are defined in Object equals() –Used for state equality testing as opposed to operator == used for reference equality –Used for test containment of object in collection –Used for storing an object in hash-based collection hashCode() –Returns an int value representing the object –Used for storing an object in hash-based collections

6 hashCode() in insertion public class SimpleHashSet { private List hashCodes = new ArrayList (); private List > lists = new ArrayList >(); public void add(Object o) { List lst = null; for(int i=0; lst==null && i<hashCodes.size(); ++i) if(hashCodes.get(i) == o.hashCode()) lst = lists.get(i); if(lst == null) { hashCodes.add(o.hashCode()); lists.add(lst = new ArrayList ()); } lst.add(o); }

7 equals, hashCode in containment test public class SimpleHashSet { … public boolean exists(Object o) { List lst = null; for(int i=0; lst==null && i<hashCodes.size(); ++i) if(hashCodes.get(i) == o.hashCode()) lst = lists.get(i); if(lst == null) return false; for(Object elem : lst) if(elem.equals(o)) return true; return false; }

8 Overriding equals() Default implementation of equals() –is based on the == operator –Two objects are equal if and only if they are the same object Sometimes a programmer specific notion of identity is required: Date d1 = new Date(2007, 7, 7); Date d2 = new Date(2007, 7, 7); d1 != d2; d1.equals(d2) == true;

9 equals() Contract The equals() method implements an equivalence relation: –It is reflexive a.equals(a) is true –It is symmetric a.equals(b) ⇔ b.equals(a) –It is transitive a.equals(b) and b.equals(c) ⇒ a.equals(c) –It is consistent repeated calls to the method must yield the same result unless the arguments are modified in-between –No object equals null a.equals(null) = false

10 equals() Contract The contract is defined in Java documentation: – s(java.lang.Object) s(java.lang.Object) The contract is not enforced by the compiler or the runtime system!

11 A Naïve Example class Point{ private final int x; private final int y; public boolean equals(Object o){ if (!(o instanceof Point)) return false; return ((Point)o).x == x && ((Point)o).y == y; } Meets all contract’s demands (as long as inheritance is not involved…)

12 Extending the Point Class class ColorPoint extends Point{ private final Color color; public boolean equals(Object o){ if (!(o instanceof ColorPoint)) return false; return super.equals(o) && ((ColorPoint)o).color == color; } ColorPoint p1 = new ColorPoint(1, 2, Color.RED); Point p2 = new Point(1, 2); p1.equals(p2); // ??? P2.equals(p1); // ???

13 Another try class ColorPoint extends Point{ final Color color; public boolean equals(Object o){ if (!(o instanceof Point)) return false; if (!(o instanceof ColorPoint)) return o.equals(this); return super.equals(o) && ((ColorPoint)o).color == color; } ColorPoint p1 = new ColorPoint(1, 2, RED); Point p2 = new Point(1, 2); ColorPoint p3 = new ColorPoint(1, 2, BLUE); p1.equals(p2); // ??? p2.equals(p3); // ??? p3.equals(p1); // ???

14 A Safe Solution class ColorPoint extends Point{ final Color color; public boolean equals(Object o){ if (o.getClass != ColorPoint.class) return false; return super.equals(o) && ((ColorPoint)o).color == color; } Meets all the contract’s requirements May be too strict An object is never equals to an instance of its super class Even if the derived class doesn’t add fields

15 Another Solution The idea: two objects must agree on their equality class Point{ … protected boolean eq(Object o) { if(!(o instanceof Point)) return false; return ((Point)o).x == x && ((Point)o).y == y; } public boolean equals(Object o){ return (this.eq(o) && o.eq(this)); } class ColorPoint extends Point{ … public boolean eq (Object o){ if (!(o instanceof ColorPoint)) return false; return super.eq(o) && ((ColorPoint)o).color == color; }

16 hashcode() Contract –It is consistent repeated calls to the method must yield the same int unless the arguments are modified in-between –Must generate equal values for equal objects We see that hashcode() is closely related to equals() if you override equals, you must override hashCode

17 hashcode / equals contract violation class Point{ final private int x, y; public boolean equals(Object o){ if (!(o instanceof Point)) return false; return ((Point)o).x == x; } public int hashCode() { return 19 * y; { } public static void main(String[] args) { Set s = new HashSet (); Point p1 = new Point(1, 2); s.add(p1); Point p2 = new Point(1, 3); //p1.equals(p2) is true System.out.println(s.contains(p2)); // false }

18 Comparable Interface Why? –equals() can compare objects of different classes –equals() is boolean – can’t be used for sorting A problem –we want compareTo to take a parameter of the same type as the receiver –requires a covariant parameter The Solution –Using generics: public interface Comparable { int compareTo(T o); }

19 Implementing Comparable public class Person implements Comparable { public String name; public int age; // Order by age then by name public int compareTo(Person p) { int diff = this.age - p.age; if(diff != 0) return diff; // Use compareTo of String return this.name.compareTo(p.name); }

20 Using compareTo() public static > void sort(List lst) { int top = lst.size(); for(int i = 0; i < top; ++i) { for(int j = i+1; j < top; ++j) { T a = lst.get(j-1); T b = lst.get(j); if(a.compareTo(b) > 0) { lst.set(j-1,b); lst.set(j, a); }

21 Comparator Interface Used for comparing objects of a class that does not implement Comparable public Interface Comparator { public int compare(T o1, T o2); } public class Utils { public static boolean isOrdered(Comparator comp, T... ts) { for(int i = 1; i < ts.length; ++i) if(comp.compare(ts[i], ts[i-1]) < 0) return false; return true; }