java type system and cloning basics 3

38
equals(…) a == b is false a.equals(b) false, if equals inherited from Object maybe true, if equals is overridden

Upload: garapatiavinash

Post on 18-Jan-2015

56 views

Category:

Documents


4 download

DESCRIPTION

 

TRANSCRIPT

  • 1. equals()a == b is falsea.equals(b)false, if equals inherited from Objectmaybe true, if equals is overridden

2. Overriding equals()public Class Vehicle {private int noOfWheels;private String name;public boolean equals(Object obj) {if (obj instanceof Vehicle) {Vehicle other = (Vehicle) obj;return (noOfWheels == other.noOfWheels) &&name.equals(other.name);} else return false;} 3. equals() and inheritancepublic Class Automobile extends Vehicle {private PowerSource power;public boolean equals(Object obj) {if (obj instanceof Automobile) {Automobile other = (Automobile) obj;return super.equals(other) &&power.equals(other.power);} else return false;} 4. equals() and inheritance Asymmetry: X.equals(Y) returns true Y.equals(X) returns false 5. perfect equals()public Class Vehicle {private int noOfWheels;private String name;public boolean equals(Object obj) {if (this == obj) return true;if (obj == null) return false;if (getClass() != obj.getClass()) return false;Vehicle obj = (Vehicle) obj;return (noOfWheels == other.noOfWheels) &&name.equals(other.name);} 6. class Student{private String name;private String idno;..........................................// Assume Accessor Methodspublic boolean equals(Object other){if(this == other) return true;if(other == null) return false;if(this.getClass() != other.getClass()) return false;Student std = (Student) other;boolean b1 = name.equals(other.getName())boolean b2 = idno.equals(other.getIdno())if(b1 && b2) return true;return false;}}Cont 7. class HostlerStudent extends Student{private int hostelCode;private String hostelName;private int roomNo;........................................// Assume Accessor Methodspublic boolean equals(Object other){if(other == null) return false;if(this.getClass() != other.getClass()) return false;if(this == other) return true;Student std = (Student) other;if(!super.equals(std)) return false;HostlerStudent hstd = (HostlerStudent) other;boolean b1 = hostelCode == other.getHostelCode();boolean b2 = roomNo == other.getRoomNo();if(b1 && b2) return true;return false;}} 8. equals() and hashing hashCode method used in HashMap, HashSet Computes an int from an object Example: hash code of Stringint h = 0;for (int i = 0; i < s.length(); i++)h = 31 * h + s.charAt(i); Hash code of "eat" is 100184 Hash code of "tea" is 114704 9. equals() and hashing Must be compatible with equals:if x.equals(y), then x.hashCode() == y.hashCode() Object.hashCode hashes memory address NOT compatible with redefined equals Remedy: Hash all fields and combine codes:public class Vehicle {public int hashCode() {return 11 * name.hashCode() +13 * new Double(noOfWheels).hashCode();}...} 10. Shallow copy Assignment x = y; 11. Shallow and Deep copy clone() method is used to make the clone or deep of the object. Example :Employee e = new Employee(..);Employee cloned = (Employee) e.clone();Assumption :Employee class supplies a suitable clone() method 12. Cloning Conditions x.clone() != x x.clone().equals(x) return true x.clone().getClass() == x.getClass() clone should be a new object but itshould be equals to its original 13. Shallow cloning clone inherited from Object makesshallow cloning x = y.clone(); 14. Deep cloning Override clone to make deep cloningx = y.clone(); 15. clone requirements Any class willing to be cloned must1. Declare the clone() method to be public2. Implement Cloneable interfaceclass Employee implements Cloneable{ public Object clone(){try { super.clone() }catch(CloneNotSupportedException e){ .. }} 16. Shallow Copy Clone() method makes a new object of the same type as theoriginal and copies all fields. But if the fields are object references then original and clonecan share common subobjects.Shallow Cloning 17. Deep Cloningpublic 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; // won't happen}}...} 18. Overriding clone()public Class Vehicle {private int noOfWheels;private PowerSource power;public Vehicle clone() {Vehicle twin = (Vehicle) super.clone();twin.power = power.clone();return twin;}}Shallow cloningDeep cloningActually, the compiler wont accept this 19. Overriding clone()Public class Object {protected Object clone() { }}public Class Vehicle implements Cloneable {public Vehicle clone() {try {Vehicle twin = (Vehicle) super.clone();twin.power = power.clone();return twin;catch (CloneNotSupportedException e) { return null; }}}Never happens 20. QUIZdeep/shallow copyHow much does viggos accounthold at end - in case ofcloning beingCustomer viggo = new Customer(2412451111,new Account(1000));Customer twin = viggo.clone();twin.getAccount().withdraw(200);Shallow? Deep?1. 1000 10002. 1000 8003. 800 10004. 800 8005. I dont know 21. class A {}class B extends A{}class C extends B{}class testA{public static void main(String args[]){Object o1 = new C();C c1 = (C) o1;B b1 = (B) o1;A a1 = (A) o1;}}ObjectABCWhats Wrong here?NOTHING>> 22. class A {}class B extends A{}class C extends B{}class testA{public static void main(String args[]){C c1 = new C();A a1 = (A) c1;B b1 = (B) c1;}}ObjectABCWhats Wrong here?NOTHING>> 23. class A {}class B extends A{}class C extends B{}class testA{public static void main(String args[]){A a1 = new A();C c1 = (C) a1;}}ObjectABCWhats Wrong here?D:OOP>java testAException in thread "main"java.lang.ClassCastException: Aat testA.main(testA.java:10) 24. class BOX{private double l,b,h;BOX(double l,double b,double h){this.l = l;this.b = b;this.h = h;}}class clonetest{public static void main(String args[]){BOX b1 = new BOX(10,6,8);BOX b2 = (BOX)b1.clone();}}D:OOP>javac clonetest.javaclonetest.java:16: clone() has protectedaccess in java.lang.ObjectBOX b2 = (BOX)b1.clone();^1 errorD:OOP> 25. class BOX{private double l,b,h;BOX(double l,double b,double h){ this.l = l;this.b = b;this.h = h;}public Object clone(){return super.clone();}}class clonetest{public static void main(String args[]){BOX b1 = new BOX(10,6,8);BOX b2 = (BOX)b1.clone();}}D:OOP>javac clonetest.javaclonetest.java:12: unreported exceptionjava.lang.CloneNotSupportedException;must be caught or declared to be thrownreturn super.clone();^1 error 26. class BOX implements Cloneable{private double l,b,h;BOX(double l,double b,double h){ this.l = l;this.b = b;this.h = h;}public Object clone(){ try{return super.clone();}catch(Exception e){ return null; }}}class clonetest{public static void main(String args[]){BOX b1 = new BOX(10,6,8);BOX b2 = (BOX)b1.clone();}} 27. import java.util.*;class datetest{public static void main(String args[]){Date d1 = new Date();Date d2 = new Date();System.out.println(d1);System.out.println(d2);System.out.println(d1.getTime());d1.setTime(1000);System.out.println(d1);}}D:OOP>java datetestSat Mar 10 22:22:40 GMT+05:30 2007Sat Mar 10 22:22:40 GMT+05:30 20071173545560812Thu Jan 01 05:30:01 GMT+05:30 1970 28. import java.util.*;class Employee implements Cloneable{private String name; // Immutable instanceprivate Date joiningDate; // Mutable instanceEmployee(String n, Date d){name =n;joiningDate =d;}public Object clone(){ try{Employee cloned = (Employee) super.clone();return cloned;}catch(CloneNotSupportedException e){ return null; }}} 29. class clonetest10{public static void main(String args[]){Employee e1 = new Employee("David", new Date());Employee e2 = (Employee) e1.clone();}}nameJoiningDatee1Davidnew Date();nameJoiningDatee2SHALLOW COPY 30. class Point{private double x,y;Point(double x, double y){ this.x =x;this.y =y;}public double getX() { return x;}public double getY() { return y;}}class Line implements Cloneable{private Point start,end;Line(Point start, Point end){ this.start = start;this.end = end;}public Object clone(){ try{Line l1 = (Line) super.clone();return l1;}catch(Exception e) {return null;}}}Immutable Class 31. class clonetest11{public static void main(String args[]){Line l1 = new Line(new Point(5,6), new Point(4,5));Line l2 = (Line) l1.clone();}}startendl1new Point(5,6),new Point(4,5),startendl2NO PROBLEM IN SHARING 32. class Point implements Cloneable{private double x,y;Point(double x, double y){ this.x =x;this.y =y;}public double getX() { return x;}public double getY() { return y;}public void setX(double x){ this.x =x;}public void setY(double x){ this.y =x;}public Object clone(){try{Point clonedPoint = (Point) super.clone();return clonedPoint;}catch(CloneNotSupportedException e){ return null; }}}> 33. class Line implements Cloneable{private Point start,end;Line(Point start, Point end){ this.start = start;this.end = end;}public Object clone(){ try{Line l1 = (Line) super.clone();l1.start = (Point) start.clone();l1.end = (Point) end.clone();return l1;}catch(Exception e) {return null;}}}Clone the mutable instance fieldsalso. 34. SUFFICIENTDEEP COPYclass clonetest11{public static void main(String args[]){Line l1 = new Line(new Point(5,6), new Point(4,5));Line l2 = (Line) l1.clone();}}startendnew Point(5,6),new Point(4,5),startendl2new Point(5,6),new Point(4,5),l1 35. import java.util.*;class Employee implements Cloneable{private String name;private Date joiningDate;Employee(String name,Date jdate){ this.name =name;joiningDate = jdate;}public String toString(){return "Name:"+name+"JoinDate:"+joiningDate;}public boolean equals(Object other){ if( other == null) return false;if( this.getClass() != other.getClass())return false;Employee emp = (Employee) other;int a = name.compareTo(emp.name);int b =joiningDate.compareTo(emp.joiningDate);return (a == 0 && b == 0);}public Object clone(){try {Employee clonedEmployee = (Employee)super.clone();clonedEmployee.joiningDate = (Date)joiningDate.clone();return clonedEmployee;}catch(CloneNotSupportedException e){ return null; }}} // End of Emplyoee class 36. class Manager extends Employee{private String dept;private double bonus;Manager(String name,Date jdate,String dept, double bonus){super(name,jdate);this.dept =dept;this.bonus = bonus;}public String toString(){return super.toString()+"Department:"+dept+"Bonus:"+bonus;}public boolean equals(Object other){ if(other == null) return false;if(this.getClass() != other.getClass())return false;if(this == other) return true;Employee emp = (Employee) other;if(!super.equals(emp)) return false;Manager m1 = (Manager) other;return (bonus== m1.bonus);}public Object clone(){Manager clonedManager =(Manager) super.clone();return clonedManager;}}// End of manager class 37. class clonetest12{public static void main(String args[]){Manager m1 = new Manager("Davis",newDate(),"Personal",2000);Manager m2 = (Manager) m1.clone();Manager m3 = new Manager("Davis",newDate(),"Personal",2000);System.out.println(m1);System.out.println(m1.equals(m2));System.out.println(m1.equals(m3));}}