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.

Slides:



Advertisements
Similar presentations
Identity and Equality Based on material by Michael Ernst, University of Washington.
Advertisements

Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Effective Java, Chapter 3: Methods Common to All Objects.
== equals ? CSE 331 SOFTWARE DESIGN & IMPLEMENTATION EQUALITY Autumn 2011.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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.
1 Building Java Programs Chapter 8: Classes These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
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.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
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.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Equality CSE 331 University of Washington. Object equality A simple idea - we have intuitions about equality: - Two objects are equal if they have the.
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.
CS/ENGRD 2110 SPRING 2015 Lecture 6: Consequence of type, casting; function equals 1.
CS/ENGRD 2110 FALL 2014 Lecture 6: Consequence of type, casting; function equals 1.
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
10-Nov-15 Java Object Oriented Programming What is it?
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 ==, equals(), and all that (Slides by David Notkin and Mike Ernst) 1.
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.
CSCI 162 Classes.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Java Type System and Object Model Horstmann ch , 7.7.
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.
1 CSE 331 Hash codes; annotations slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
CSC142 NN 1 CSC 142 Overriding methods from the Object class: equals, toString.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
1 CSE 331 Comparing objects; Comparable, compareTo, and Comparator slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
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.
Lecture 25: Inheritance and Polymorphism
Building Java Programs Chapter 9
Lecture 17: Polymorphism (Part II)
CSE 331 Software Design and Implementation
Overloading and Constructors
CSE 331 Cloning objects slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CSE 143 Lecture 22 The Object class; Polymorphism read
Testing, cont., Equality and Identity
Extending Classes.
CS/ENGRD 2110 Fall 2018 The fattest knight at King Arthur's round table was Sir Cumference. He acquired his size from too much pi. Lecture 6: Consequence.
Fall 2018 CISC124 12/3/2018 CISC124 or talk to your grader with questions about assignment grading. Fall 2018 CISC124 - Prof. McLeod Prof. Alan McLeod.
CSE 143 Lecture 22 The Object class; Polymorphism read
Building Java Programs
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Lecture 18: Polymorphism (Part II)
CSE 373 Objects in Collections: Object; equals; compareTo; mutability
Lecture 25: Inheritance and Polymorphism
Java Programming Language
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Special instance methods: toString
CSE 143 Lecture 23 Polymorphism; the Object class read
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
CMPE212 – Reminders Assignment 2 due next Friday.
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Building Java Programs
Presentation transcript:

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. Mercer, Wikipedia

2 The class Object The class Object forms the root of the overall inheritance tree of all Java classes.  Every class is implicitly a subclass of Object The Object class defines several methods that become part of every class you write. For example:  public String toString() Returns a text representation of the object, usually so that it can be printed.

3 Object methods  What does this list of methods tell you about Java's design? methoddescription protected Object clone() creates a copy of the object public boolean equals(Object o) returns whether two objects have the same state protected void finalize() called during garbage collection public Class getClass() info about the object's type public int hashCode() a code suitable for putting this object into a hash collection public String toString() text representation of the object public void notify() public void notifyAll() public void wait() public void wait(...) methods related to concurrency and locking (seen later)

4 Common properties of objects When Sun designed Java, they felt that every object (including arrays) should be able to:  be compared to other objects (equals)  be printed on the console or converted into a string (toString)  ask questions at runtime about what type/class it is (getClass)  be created (constructors), copied (clone), and destroyed (finalize)  be used in hash-based collections (hashCode)  perform multi-threaded synchronization and locking (notify/wait) This powerful and broad set of capabilities helped Java's adoption as an object-oriented language.

5 Using the Object class You can store any object in a variable of type Object. Object o1 = new Point(5, -3); Object o2 = "hello there"; You can write methods that accept an Object parameter. public void example(Object o) { if (o != null) { System.out.println( "o is " + o.toString() ); } You can make arrays or collections of Object s. Object[] a = new Object[5]; a[0] = "hello"; a[1] = new Random(); List list = new ArrayList ();

6 Recall: comparing objects The == operator does not work well with objects. == tests for referential equality, not state-based equality. It produces true only when you compare an object to itself. Point p1 = new Point(5, 3); Point p2 = new Point(5, 3); Point p3 = p2; // p1 == p2 is false; // p1 == p3 is false; // p2 == p3 is true // p1.equals(p2)? // p2.equals(p3)?... x 5 y 3 p1 p2... x 5 y 3 p3

7 Default equals method The Object class's equals implementation is very simple: public class Object {... public boolean equals(Object o) { return this == o; } However:  When we have used equals with various kinds of objects, it didn't behave like ==. Why not?  The Java API documentation for equals is elaborate. Why?Java API documentation for equals

8 Overriding equals The Object class is designed for inheritance.  Its description and specification will apply to all other Java classes. So, its specification must be flexible enough to apply to all classes.  Subclasses will override equals to test for equality in their own way.  The Object equals spec enumerates basic properties that clients can rely on that method to have in all subtypes of Object. (this == o) is compatible with these properties, but so are other tests.

9 Flawed equals method 1 public boolean equals(Point other) { // bad if (x == other.x && y == other.y) { return true; } else { return false; } } Let's write an equals method for a Point class.  The method should compare the state of the two objects and return true if they have the same x/y position.  What's wrong with the above implementation?

10 Flaws in the method The body can be shortened to the following (boolean zen): return x == other.x && y == other.y; The parameter to equals must be of type Object, not Point.  It should be legal to compare a Point to any other object: // this should be allowed Point p = new Point(7, 2); if (p.equals("hello")) { // false...  equals should always return false if a non- Point is passed.  By writing ours to accept a Point, we have overloaded equals. Point has two equals methods: One takes an Object, one takes a Point.

11 Flawed equals method 2 public boolean equals(Object o) { // bad return x == o.x && y == o.y; } What's wrong with the above implementation?  It does not compile: Point.java:36: cannot find symbol symbol : variable x location: class java.lang.Object return x == o.x && y == o.y; ^  The compiler is saying, " o could be any object. Not every object has an x field."

12 Object variables You can store any object in a variable of type Object. Object o1 = new Point(5, -3); Object o2 = "hello there"; Object o3 = new Scanner(System.in); An Object variable only knows how to do general things. String s = o1.toString(); // ok int len = o2.length(); // error String line = o3.nextLine(); // error  (The objects referred to by o1, o2, and o3 still do have those methods. They just can't be called through those variables because the compiler isn't sure what kind of object the variable refers to.)

13 Casting references Object o1 = new Point(5, -3); Object o2 = "hello there"; ((Point) o1).translate(6, 2); // ok int len = ((String) o2).length(); // ok Point p = (Point) o1; int x = p.getX(); // ok Casting references is different than casting primitives.  Doesn't actually change the object that is referred to.  Tells the compiler to assume that o1 refers to a Point object. Watch out for precedence mistakes: int len = (String) o2.length(); // error

14 Flawed equals method 3 public boolean equals(Object o) { Point other = (Point) o; return x == other.x && y == other.y; } What's wrong with the above implementation?  It compiles and works when other Point objects are passed, but it throws an exception when a non- Point is passed (see next slide).

15 Comparing different types Point p = new Point(7, 2); if (p.equals("hello")) { // should be false... }  Currently our method crashes on the above code: Exception in thread "main" java.lang.ClassCastException: java.lang.String at Point.equals(Point.java:25) at PointMain.main(PointMain.java:25)  The problem is the cast (cannot cast sideways in an inheritance tree): public boolean equals(Object o) { Point other = (Point) o;

16 The instanceof keyword reference instanceof type if ( variable instanceof type ) { statement(s) ; } A binary, infix, boolean operator. Tests whether variable refers to an object of class type (or any subclass of type). String s = "hello"; Point p = new Point(); expressionresult s instanceof Pointfalse s instanceof Stringtrue p instanceof Pointtrue p instanceof Stringfalse p instanceof Objecttrue s instanceof Objecttrue null instanceof Stringfalse null instanceof Objectfalse

17 Flawed equals method 4 // Returns true if o refers to a Point object // with the same (x, y) coordinates as // this Point; otherwise returns false. public boolean equals(Object o) { if (o instanceof Point) { Point other = (Point) o; return x == other.x && y == other.y; } else { return false; } } What's wrong with the above implementation?  It behaves incorrectly if the Point class is extended (see next slides).

18 Subclassing and equals public class Point3D extends Point { private int z; public Point3D(int x, int y, int z) {... }... } Point3D p1 = new Point3D(4, 5, 0); Point3D p2 = new Point3D(4, 5, 6); Point p3 = new Point (4, 5); All objects above will report that they are "equal" to each other.  But they shouldn't be. The objects don't have equal state.  In some cases, they aren't even the same type.

19 Flawed equals method 5 public class Point3D extends Point {... public boolean equals(Object o) { if (o instanceof Point3D) { Point3D other = (Point3D) o; return super.equals(o) && z == other.z; } else { return false; } } } What's wrong with the above implementation?  It produces asymmetric results when Point and Point3D are mixed.

20 A proper equals method Equality is reflexive:  a.equals(a) is true for every object a Equality is symmetric:  a.equals(b) ↔ b.equals(a) Equality is transitive:  (a.equals(b) && b.equals(c)) ↔ a.equals(c) No non- null object is equal to null :  a.equals(null) is false for every object a Effective Java Tip #8: Obey the general contract when overriding equals.

21 The getClass method getClass returns information about the type of an object.  Commonly used for reflection (seen later).  Uses run-time type information, not the type of the variable.  Stricter than instanceof ; subclasses return different results. getClass should be used when implementing equals.  Instead of instanceof to check for same type, use getClass.  This will eliminate subclasses from being considered for equality.  Caution: Must check for null before calling getClass.

22 Correct equals methods public boolean equals(Object o) { // Point if (o != null && getClass() == o.getClass()) { Point other = (Point) o; return x == other.x && y == other.y; } else { return false; } public boolean equals(Object o) { // Point3D if (o != null && getClass() == o.getClass()) { Point3D other = (Point3D) o; return super.equals(o) && z == other.z; } else { return false; }

23 Equality and time If two objects are equal now, will they always be equal?  In mathematics, the answer is "yes".  In Java, the answer is "you choose".  The Object contract doesn't specify this (why not?) For mutable objects, equality may change if objects change. For immutable objects (ones with no "setter" mutator methods):  The object's state never changes.  Equality is automatically forever.

24 Equality and time example The following objects start out equal but are later unequal: Date d1 = new Date(0); // Jan :00:00 GMT Date d2 = new Date(0); System.out.println(d1.equals(d2)); // true d2.setTime(1); // 1 millisecond later System.out.println(d1.equals(d2)); // false

25 Kinds of equivalence Two objects are behaviorally equivalent if:  There is no sequence of operations that can distinguish them.  This is "eternal" equality.  Two Strings with same content are behaviorally equivalent, two Dates with same content are not. Two objects are observationally equivalent if:  There is no sequence of operations that can distinguish them without using == or calling mutator methods on the object(s).  Two Strings or Dates with same content are observationally equivalent.

26 Equality and collections Set set1 = new HashSet (); Set set2 = new TreeSet (); for (String s : "hi how are you".split(" ")) { set1.add(s); set2.add(s); } System.out.println(set1.equals(set2)); // true Objects of different types are usually not equals to each other. But the documentation for the Set interface specifies:  Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.