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.

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Identity and Equality Based on material by Michael Ernst, University of Washington.
Programo Issues Cora Pérez Ariza ~ DECSAI ~ UGR Granada, January 28 th & 29 th, 2009.
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.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Searching and Sorting I 1 Searching and Sorting 1.
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.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
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.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Chapter 4 Linked Lists Anshuman Razdan Div of Computing Studies
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
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.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
(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[]
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
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[]
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.
Not overriding equals  what happens if you do not override equals for a value type class?  all of the Java collections will fail in confusing ways 1.
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
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 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Symbol Tables From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Java Type System and Object Model Horstmann ch , 7.7.
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.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
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.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance INHERITANCE: extend existing classes by adding or redefining methods, and adding instance fields Suppose we have a class Vehicle: public class.
The Object class Object package java.lang Object clone equals hashCode toString aCopy toThis hash string ! yesOrNo.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
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.
Chapter 13 - Inheritance.
Object-Oriented Concepts
Searching.
Object-oriented Programming in Java
03/10/14 Inheritance-2.
CSC 205 Java Programming II
Non-static classes.
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
Testing, cont., Equality and Identity
Building Java Programs
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Effective Java, Chapter 3, 3rd Edition: Methods Common to All Objects
Searching.
CS/ENGRD 2110 Spring 2019 Lecture 6: Consequence of type, casting; function equals
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
Chapter 7 Java Object Model
Presentation transcript:

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 of Object Methods of Object include: –String toString() –boolean equals (Object other) –int hashCode() –Object clone()

3 Method toString() Returns String representation of object; describes state of object Automatically called when: –Object is concatenated with a String –Object is printed using print() or println() –Object reference is passed to assert statement of the form: assert condition : object

4 Example Rectangle r = new Rectangle (0,0,20,40); System.out.println(r); Prints out: java.awt.Rectangle[x=0,y=0,width=20,height=40]

5 More on toString() Default toString() method just prints (full) class name & hash code of object Not all API classes override toString() Good idea to implement for debugging purposes: –Should return String containing values of important fields along with their names –Should also return result of getClass().getName() rather than hard-coded class name

6 Overriding toString(): example public class Employee { public String toString() { return getClass().getName() + "[name=" + name + ",salary=" + salary + "]"; }... } Typical String produced: Employee[name=John Doe,salary=40000]

7 Overriding toString in a subclass Format superclass first Add unique subclass details Example: public class Manager extends Employee { public String toString() { return super.toString() + "[department=" + department + "]"; }... }

8 Example continued Typical String produced: Manager[name=Mary Lamb,salary=75000][department=Admin] Note that superclass reports actual class name

9 Equality testing Method equals() tests whether two objects have same contents By contrast, == operator test 2 references to see if they point to the same object (or test primitive values for equality) Need to define for each class what “equality” means: –Compare all fields –Compare 1 or 2 key fields

10 Equality testing Object.equals tests for identity: public class Object { public boolean equals(Object obj) { return this == obj; }... } Override equals if you don't want to inherit that behavior

11 Overriding equals() Good practice to override, since many API methods assume objects have well-defined notion of equality When overriding equals() in a subclass, can call superclass version by using super.equals()

12 Requirements for equals() method reflexiveMust be reflexive: for any reference x, x.equals(x) is true symmetricMust be symmetric: for any references x and y, x.equals(y) is true if and only if y.equals(x) is true transitiveMust be transitive: if x.equals(y) and y.equals(z), then x.equals(z) If x is not null, then x.equals(null) must be false

13 The perfect equals() method public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false;... }

14 Hashing Technique used to find elements in a data structure quickly, without doing full linear search Important concepts: –Hash code: integer value used to find array index for data storage/retrieval –Hash table: array of elements arranged according to hash code –Hash function: computes hash code for element; uses algorithm likely to produce different hash codes for different objects to minimize collisions

15 Hashing in Java Java library contains HashSet and HashMap classes –Use hash tables for data storage –Since Object has a hashCode method (hash function), any type of object can be stored in a has table

16 Default hashCode() Hashes memory address of object; consistent with default equals() method If you override equals(), you should also redefine hashCode() For class you are defining, use product of hash of each field and a prime number, then add these together – result is hash code

17 Example public class Employee { public int hashCode() { return 11 * name.hashCode() + 13 * new Double(salary).hashCode(); }... }

18 Object copying Shallow copy –Copy of an object reference is another reference to the same object –Happens with assignment operator Deep copy –Actual new object created, identical to original –A.K.A cloning

19 Method clone() must fulfill 3 conditions X.clone() != X X.clone().equals(X) X.clone().getClass() == X.getClass()

20 Object.clone() Default method is protected If a class wants clients to be able to clone its instances, must: –Redefine clone() as public method –Implement Cloneable interface

21 Cloneable Interface that specifies no methods: public interface Cloneable {} Strictly “tagging” interface; can be used to test if object can be cloned: if (x instanceof Cloneable) … If class doesn’t implement this interface, Object.clone() throws a CloneNotSupportedException (checked)

22 Example clone() method (v 1.0) public class Employee implements Cloneable { public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { return null; // won't happen } }... }

23 Shallow cloning Object.clone() uses assignment – makes shallow copy of all fields If fields are object references, original and clone share common subobjects Not a problem for immutable fields (e.g. Strings) but programmer-written clone() methods must clone mutable fields Rule of thumb: if you extend a class that defines clone(), redefine clone()

24 Example clone() method (v 2.0) public class Employee implements Cloneable { public Object clone() { try { Employee cloned = (Employee) super.clone(); cloned.hireDate = (Date) hireDate.clone(); return cloned; } catch(CloneNotSupportedException e) { return null; } }... }