logging in or signing up Objects Woodwork Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINT Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 502 Category: Entertainment License: All Rights Reserved Like it (0) Dislike it (0) Added: August 22, 2007 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... Premium member Presentation Transcript Objects: Objects Copyright Kip Irvine, 2003. All rights reserved. Only students enrolled in COP 4338 at Florida International University may copy or print the contents of this slide show. Some materials used here are from Mark Allen Weiss, used by permission. By Kip Irvine Last update: 8/29/2003 Overview: Overview java.lang.Object class Comparing Class Types toString( ) Object.equals( ) Object.hashCode( ) Object.clone( ) Implementing clone( ) Practice java.lang.Object Class: java.lang.Object Class Extended by all other classes (directly or indirectly) Not abstract Defines standard set of methods that apply to all non-primitives permits generic code to handle all types of objects common interface for all objects, such as toString( ), clone( ) and equals( ) java.lang.Object Methods: java.lang.Object Methods Class getClass( ) String toString( ) boolean equals( Object other ) int hashCode( ) Object clone( ) java.lang.Object Methods (cont): java.lang.Object Methods (cont) void finalize( ) called by the garbage collector on an object when no references to the object exist. wait( ) causes current thread to wait until notifyAll( ) is executed by another thread notifyAll( ) wakes up all threads waiting on the object's monitor object.getClass( ): object.getClass( ) Returns the Class of the current object Class getClass( ) Every type has a single Class object that represents its runtime class Contains type information such as methods, fields, class name, superclass, etc. Example: String s = new String( ); Class c1 = s.getClass( ); See: GetClass.java (The Reflection lecture will deal with the Class class.) Comparing Class Types: Comparing Class Types Objects related by inheritance have difference class types: class Dog { . . . } class Poodle extends Dog { . . . } Object fluffy = new Poodle( ); Object flopsie = new Poodle( ); Object fido = new Dog( ); Class c1 = fluffy.getClass( ); Class c2 = flopsie.getClass( ); Class c3 = fido.getClass( ); // c1 == c2, but c1 != c3 toString( ): toString( ) Default implementation prints name of class and hexadecimal hash code distinct objects having the same state will have different hash codes How to Implement toString( ): Chain backward to super.toString( ) Call each field's toString( ) method Don't hard-code class name (why? see next slide) Example: toString.java If subclass doesn't overload toString( ), the implementation in base class can be misleading:: If subclass doesn't overload toString( ), the implementation in base class can be misleading: class Person { private int id; public String toString() { return 'Person[' + id + ']'; } } class Student extends Person { . . . } Student S = new Student( 1024 ); System.out.println( S.toString( ) ); // output: 'Person[1024]' This is more flexible:: This is more flexible: class Person { private int id; public String toString() { return getClass().getName() + '[' + id + ']'; } } class Student extends Person { . . . } Student S = new Student( 1024 ); System.out.println( S.toString( ) ); // output: 'Student[1024]' Object.equals( ): Object.equals( ) Object class provides the strictest test: for reference values x and y, equals( ) returns true if and only if x and y refer to the same object (i.e. x == y ). Overriding equals( ) in your own class: provide your own semantics for comparing objects call super.equals( ) first Signature: public boolean equals( Object obj ) required! equals( ) contract:: equals( ) contract: if either object is null, equals( ) returns false if classes are different, equals( ) returns false reflexive: x.equals( x ) must be true symmetric: x.equals( y ) returns same value as y.equals( x ) transitive: x.equals( y ) andamp;andamp; y.equals( z ) implies x.equals( z ) equals( ) must be consistent with hashCode( ) How Not to Implement Equals: How Not to Implement Equals class Person { public boolean equals( Object rhs ) { if( !( rhs instanceof Person ) ) return false; return name.equals( ( (Person) rhs ).name ); } class Hero { public boolean equals( Object rhs ) { if( !( rhs instanceof Hero ) ) return false; return talent.equals( ( (Hero) rhs ).talent ); } } Using instanceof: Violates Symmetry Rule: Violates Symmetry Rule Person p = new Person( 'Superman' ); Hero h = new Hero( 'Superman', 'flies fast' ); System.out.println( 'p.equals( h ): ' + p.equals( h ) ); System.out.println( 'h.equals( p ): ' + h.equals( p ) ); When p.equals( h ) calls Person.equals( ), (instanceof Person) returns true When h.equals( p ) calls Hero.equals ( ), (instanceof Hero) returns false See badEquals.java For the correct way to do it, see goodEquals.java Object.hashCode( ): Object.hashCode( ) Used as key value in hashTable, hashSet, and hashMap containers Relation to the equals( ) method: If x.equals( y ) is true, the values returned by their hashCode( ) functions must be the same. If x.equals( y ) is false, their hashCode( ) return values need not be different (but it’s better if they are) Override Object.hashCode( ) to generate your own hash code based on the object's state See: HashCode.java Object.clone( ): Object.clone( ) Copying the state of an object not its reference! Object.clone( ) is declared protected Throws CloneNotSupportedException Semantics: (x.clone( ) != x) is generally true (x.clone( ).getClass( ) == x.getClass( )) is generally true (x.clone( ).equals(x)) is generally true Implementing clone( ): Implementing clone( ) This does not copy an object: Person P1 = new Person(...); Person P2 = P1; Requirements: never call constructor to make a copy; instead, call super.clone( ) implement Cloneable( ) interface arrays automaticaly implement Cloneable call clone( ) on each mutable reference field must cast objects to current class Signature: public Object clone( ) throws CloneNotSupportedException See CloneTest.java and ObjectDemo.java Why constructor calls don't work: Why constructor calls don't work Object class contract for clone( ) states that no constructor is called Subclass returns wrong type from clone when a constructor is used in andlt;baseClassandgt;.clone( ) Bad clone( ) Example: Bad clone( ) Example Suppose Person.clone( ) calls constructor: public class Person implements Cloneable { public Person ( andlt;parametersandgt; ) { } public Object clone( ) throws CloneNotSupportedException { return new Person( andlt;parametersandgt; ); } } clone( ) Example: clone( ) Example Then the child class cannot call super.clone( ) and cast the result into its own class type: public class Student extends Person { private Date enrollDate; public Object clone( ) throwsCloneNotSupportedException { // oops: this throws a ClassCastException: Student stu = (Student)super.clone( ); if( enrollDate != null ) stu.enrollDate = (Date)enrollDate.clone( ); return stu; } } Practice: Practice Open the HeroTest.java file Rename it to HeroTestDone.java, and rename the HeroTest class to HeroTestDone. Implement toString( ), equals( ), clone( ), and hashCode( ) for the Hero and SuperHero classes. Sample Output: Sample Output h1 = Green Lantern true Wed Jan 04 00:00:00 HST 1950 evaluating (h1.equals(h3)): false h2 = Hercules p2 = Hercules evaluating (h2.equals(p2)): false h2 = Samson ------------ clones follow --------------- h3 is a clone of h1 hash codes: h3=nnnnnnnn, h1=nnnnnnnn 1 evaluating (h3 == h1): false evaluating (h3.equals(h1)): true h4 is a clone of h3 evaluating (h4.equals(h3)): true evaluating (h4.equals(h1)): true 1 hash code for h3 must equal hash code for h1 The End: The End example: example code text Class Example: Class Example Shape s1 = new Rectangle( new Point(1,1), new Point(50,60) ); Class c1 = s1.getClass( ); System.out.println( s1 ); System.out.println( 'type of s1 is ' + c1 ); System.out.println( c1.toString() ); System.out.println( c1.getName() ); output: Rectangle@5d87b2 type of s1 is class Rectangle class Rectangle Rectangle You do not have the permission to view this presentation. In order to view it, please contact the author of the presentation.
Objects Woodwork Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINT Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 502 Category: Entertainment License: All Rights Reserved Like it (0) Dislike it (0) Added: August 22, 2007 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... Premium member Presentation Transcript Objects: Objects Copyright Kip Irvine, 2003. All rights reserved. Only students enrolled in COP 4338 at Florida International University may copy or print the contents of this slide show. Some materials used here are from Mark Allen Weiss, used by permission. By Kip Irvine Last update: 8/29/2003 Overview: Overview java.lang.Object class Comparing Class Types toString( ) Object.equals( ) Object.hashCode( ) Object.clone( ) Implementing clone( ) Practice java.lang.Object Class: java.lang.Object Class Extended by all other classes (directly or indirectly) Not abstract Defines standard set of methods that apply to all non-primitives permits generic code to handle all types of objects common interface for all objects, such as toString( ), clone( ) and equals( ) java.lang.Object Methods: java.lang.Object Methods Class getClass( ) String toString( ) boolean equals( Object other ) int hashCode( ) Object clone( ) java.lang.Object Methods (cont): java.lang.Object Methods (cont) void finalize( ) called by the garbage collector on an object when no references to the object exist. wait( ) causes current thread to wait until notifyAll( ) is executed by another thread notifyAll( ) wakes up all threads waiting on the object's monitor object.getClass( ): object.getClass( ) Returns the Class of the current object Class getClass( ) Every type has a single Class object that represents its runtime class Contains type information such as methods, fields, class name, superclass, etc. Example: String s = new String( ); Class c1 = s.getClass( ); See: GetClass.java (The Reflection lecture will deal with the Class class.) Comparing Class Types: Comparing Class Types Objects related by inheritance have difference class types: class Dog { . . . } class Poodle extends Dog { . . . } Object fluffy = new Poodle( ); Object flopsie = new Poodle( ); Object fido = new Dog( ); Class c1 = fluffy.getClass( ); Class c2 = flopsie.getClass( ); Class c3 = fido.getClass( ); // c1 == c2, but c1 != c3 toString( ): toString( ) Default implementation prints name of class and hexadecimal hash code distinct objects having the same state will have different hash codes How to Implement toString( ): Chain backward to super.toString( ) Call each field's toString( ) method Don't hard-code class name (why? see next slide) Example: toString.java If subclass doesn't overload toString( ), the implementation in base class can be misleading:: If subclass doesn't overload toString( ), the implementation in base class can be misleading: class Person { private int id; public String toString() { return 'Person[' + id + ']'; } } class Student extends Person { . . . } Student S = new Student( 1024 ); System.out.println( S.toString( ) ); // output: 'Person[1024]' This is more flexible:: This is more flexible: class Person { private int id; public String toString() { return getClass().getName() + '[' + id + ']'; } } class Student extends Person { . . . } Student S = new Student( 1024 ); System.out.println( S.toString( ) ); // output: 'Student[1024]' Object.equals( ): Object.equals( ) Object class provides the strictest test: for reference values x and y, equals( ) returns true if and only if x and y refer to the same object (i.e. x == y ). Overriding equals( ) in your own class: provide your own semantics for comparing objects call super.equals( ) first Signature: public boolean equals( Object obj ) required! equals( ) contract:: equals( ) contract: if either object is null, equals( ) returns false if classes are different, equals( ) returns false reflexive: x.equals( x ) must be true symmetric: x.equals( y ) returns same value as y.equals( x ) transitive: x.equals( y ) andamp;andamp; y.equals( z ) implies x.equals( z ) equals( ) must be consistent with hashCode( ) How Not to Implement Equals: How Not to Implement Equals class Person { public boolean equals( Object rhs ) { if( !( rhs instanceof Person ) ) return false; return name.equals( ( (Person) rhs ).name ); } class Hero { public boolean equals( Object rhs ) { if( !( rhs instanceof Hero ) ) return false; return talent.equals( ( (Hero) rhs ).talent ); } } Using instanceof: Violates Symmetry Rule: Violates Symmetry Rule Person p = new Person( 'Superman' ); Hero h = new Hero( 'Superman', 'flies fast' ); System.out.println( 'p.equals( h ): ' + p.equals( h ) ); System.out.println( 'h.equals( p ): ' + h.equals( p ) ); When p.equals( h ) calls Person.equals( ), (instanceof Person) returns true When h.equals( p ) calls Hero.equals ( ), (instanceof Hero) returns false See badEquals.java For the correct way to do it, see goodEquals.java Object.hashCode( ): Object.hashCode( ) Used as key value in hashTable, hashSet, and hashMap containers Relation to the equals( ) method: If x.equals( y ) is true, the values returned by their hashCode( ) functions must be the same. If x.equals( y ) is false, their hashCode( ) return values need not be different (but it’s better if they are) Override Object.hashCode( ) to generate your own hash code based on the object's state See: HashCode.java Object.clone( ): Object.clone( ) Copying the state of an object not its reference! Object.clone( ) is declared protected Throws CloneNotSupportedException Semantics: (x.clone( ) != x) is generally true (x.clone( ).getClass( ) == x.getClass( )) is generally true (x.clone( ).equals(x)) is generally true Implementing clone( ): Implementing clone( ) This does not copy an object: Person P1 = new Person(...); Person P2 = P1; Requirements: never call constructor to make a copy; instead, call super.clone( ) implement Cloneable( ) interface arrays automaticaly implement Cloneable call clone( ) on each mutable reference field must cast objects to current class Signature: public Object clone( ) throws CloneNotSupportedException See CloneTest.java and ObjectDemo.java Why constructor calls don't work: Why constructor calls don't work Object class contract for clone( ) states that no constructor is called Subclass returns wrong type from clone when a constructor is used in andlt;baseClassandgt;.clone( ) Bad clone( ) Example: Bad clone( ) Example Suppose Person.clone( ) calls constructor: public class Person implements Cloneable { public Person ( andlt;parametersandgt; ) { } public Object clone( ) throws CloneNotSupportedException { return new Person( andlt;parametersandgt; ); } } clone( ) Example: clone( ) Example Then the child class cannot call super.clone( ) and cast the result into its own class type: public class Student extends Person { private Date enrollDate; public Object clone( ) throwsCloneNotSupportedException { // oops: this throws a ClassCastException: Student stu = (Student)super.clone( ); if( enrollDate != null ) stu.enrollDate = (Date)enrollDate.clone( ); return stu; } } Practice: Practice Open the HeroTest.java file Rename it to HeroTestDone.java, and rename the HeroTest class to HeroTestDone. Implement toString( ), equals( ), clone( ), and hashCode( ) for the Hero and SuperHero classes. Sample Output: Sample Output h1 = Green Lantern true Wed Jan 04 00:00:00 HST 1950 evaluating (h1.equals(h3)): false h2 = Hercules p2 = Hercules evaluating (h2.equals(p2)): false h2 = Samson ------------ clones follow --------------- h3 is a clone of h1 hash codes: h3=nnnnnnnn, h1=nnnnnnnn 1 evaluating (h3 == h1): false evaluating (h3.equals(h1)): true h4 is a clone of h3 evaluating (h4.equals(h3)): true evaluating (h4.equals(h1)): true 1 hash code for h3 must equal hash code for h1 The End: The End example: example code text Class Example: Class Example Shape s1 = new Rectangle( new Point(1,1), new Point(50,60) ); Class c1 = s1.getClass( ); System.out.println( s1 ); System.out.println( 'type of s1 is ' + c1 ); System.out.println( c1.toString() ); System.out.println( c1.getName() ); output: Rectangle@5d87b2 type of s1 is class Rectangle class Rectangle Rectangle