1 / 32

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010. Interfaces (Part II). “A picture is worth a thousand words. An interface is worth a thousand pictures.” -Ben Shneiderman. Course Lecture Slides 28 June 2010. Ganesh Viswanathan. Interface.

Download Presentation

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Interfaces (Part II) “A picture is worth a thousand words. An interface is worth a thousand pictures.” -Ben Shneiderman Course Lecture Slides28June 2010 GaneshViswanathan

  2. Interface • Language construct that specifies functionality without any hint at implementation. • An interface contains method specifications but no method implementations.

  3. Comparable Interface // Interface defined in java.lang package public interface Comparable { public intcompareTo(Object o); } • compareTo( ) • Compares this object with the specified object for order. • Returns a negative integer, zero or a positive integer when this object is less than, equal to or greater than the specified object. • Throws:ClassCastExceptionif the specified object's type prevents it from being compared to this Object.

  4. Declaring Classes to Implement Comparable

  5. public class ComparableRectangle extends Rectangle implements Comparable { public ComparableRectangle(double width, double height){ super(width, height); } // Implement the compareTo method defined in Comparable public intcompareTo(Object o) { ComparableRectanglecr = (ComparableRectangle)o; if (getArea() > cr.getArea()) return 1; else if(getArea() < cr.getArea()) return -1; else return 0; } }

  6. Using Arrays.sort() • If you have an array of objects of some class C and you want to use Arrays.sort(Object[] a) or Arrays.sort(Object[] a, intfromIndex, inttoIndex) to sort this array, you must make class C implement Comparable interface • The above sort() methods use the compareTo() method to compare two array elements of reference type

  7. Arrays.Sort() • What if you want to sort this array of objects in order of different attributes of class C at different times? • Solution: Use Arrays.sort(Object[] a, Comparator c) Or Arrays.sort(Object[] a, intfromIndex, inttoIndex, Comparator c)

  8. Comparator Interface public interface Comparator { public intcompare(Object o1, Object o2) } Returns: a negative integer, zero, or a positive integer when the first argument is less than,equal to, or greater thanthe second. Throws:ClassCastException - if the arguments' types prevent them from being compared by this Comparator.

  9. Solution • Create a class that implements the Comparator interface • Code the compare() method to define the ordering between objects of this class • Pass an instance of this class to the Arrays.Sort() method

  10. Another scenario • What if • you are using a class C which does not implement the Comparable interface • You do not have access to C.java file • You only have access to the C.class file • And you want to sort an arrays of objects of class C in order of some attribute of the class

  11. Solution • Create a class that implements the Comparator interface • Code the compare() method to define the ordering between objects of this class

  12. Another Advantage of using interfaces as data types public class Max { public static Comparable max(? o1, ? o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } } ComparableRectangle rectangle1 = new ComparableRectangle(4, 5); ComparableRectangle rectangle2 = new ComparableRectangle(3, 6); System.out.println(Max.max(rectangle1, rectangle2));

  13. Another Advantage of using interfaces as data types public class Max { public static Comparable max(Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } } ComparableRectangle rectangle1 = new ComparableRectangle(4, 5); ComparableRectangle rectangle2 = new ComparableRectangle(3, 6); System.out.println(Max.max(rectangle1, rectangle2));

  14. Interfaces, cont • Max method in (a) is more robust.

  15. Get more info! • Tutorial: • http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html • Comparable vs. Comparator: • http://grdurand.com/static/presentation_four/comparable.html • Using comparable: • http://onjava.com/pub/a/onjava/2003/03/12/java_comp.html

  16. Use Comparable(implement compareTo( ) method): • if you want to compare based on the default natural ordering. • if the object is in your control. • Use Comparator (implement compare( ) method): • if you want comparing behavior different from the expected default (which is specified by Comparable). • if the object is outside your control and you cannot make them implement Comparable.

  17. “Object Ordering”Reference: Java Docs See supporting code (TestComparator.java)

  18. Object Duplication • Shallow Copy and Deep Copy • Using Java’s Cloneable interface

  19. Shallow Copy • Bit-wise copy of an object. • A new object created with an exact copy of the values in the original object. • If any of the fields of the object are referencesto other objects, only the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same sub-objects.

  20. Deep Copy • Complete duplicate copy of an object. • If an object has references to other objects, complete new copies of those objects are also made. • A deep copy generates a copy not only of the primitive values of the original object, but copies of all sub-objects as well, all the way to the bottom. To get a true, complete copy of the original object, you will need to override the default object.clone() to implement a full deep copy for the object.

  21. The Cloneable Interface • It is a Marker Interface i.e. • it does not contain constants or methods. • Defined in the java.lang package as follows: package java.lang; public interface Cloneable { }

  22. Examples Many classes (e.g., Date and Calendar) in the Java library implement Cloneable. Thus, the instances of these classes can be cloned.For example, the following code outputs • Calendar calendar = new GregorianCalendar(2003, 2, 1); • Calendar calendarCopy = (Calendar)calendar.clone(); • System.out.println("calendar == calendarCopy is " + • (calendar == calendarCopy)); • System.out.println("calendar.equals(calendarCopy) is " • + calendar.equals(calendarCopy)); • calendar == calendarCopy is false • calendar.equals(calendarCopy) is true

  23. Implementing Cloneable Interface • A class that implements the Cloneable interface must override the clone() method • in the Object class.

  24. public class House implements Cloneable{ private int id; private double area; public House(int id, double area) { this.id = id; this.area = area; } public double getId() { return id; } public double getArea() { return area; } public Object clone() throws CloneNotSupportedException { return super.clone(); } }

  25. public class House implements Cloneable{ private int id; private double area; private java.util.DatewhenBuilt; public House(int id, double area) { this.id = id; this.area = area; whenBuilt = new java.util.Date(); } public double getId() { return id; } public double getArea() { return area; } public java.util.DategetWhenBuilt(){ return whenBuilt; } public Object clone() throws CloneNotSupportedException { return super.clone(); } }

  26. Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone();

  27. public class House implements Cloneable{ private int id; private double area; private java.util.DatewhenBuilt; // other code public Object clone() throws CloneNotSupportedException { House house = (House)super.clone(); house.whenBuilt = (java.util.Date)(whenBuilt.clone()); return house; } } All mutable fields should be cloned to get a deep copy. Strings are immutable, so there is no need to clone String type attributes separately.

  28. public class House implements Cloneable{ private int id; private double area; private String name; public House(int id, double area) { this.id = id; this.area = area; whenBuilt = new java.util.Date(); } public double getId() { return id; } public double getArea() { return area; } public java.util.Date getWhenBuilt(){ return whenBuilt; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } Is the clone() method doing deep copy?

  29. Can the clone() method be written as follows? class House implements Cloneable { private intnumberOfRooms; private intsquareFeet; //... public Object clone() throws CloneNotSupportedException { return new House(numberOfRooms, squareFeet); } }

  30. What happens when the following code is executed? public class MultiStoryHouse extends House { private intnumberOfStories; public MultiStoryHouse(intnumRooms, intsqFootage, intnumStories) { super(numRooms, sqFootage); numberofStories = numStories; } // no clone method defined } public class Driver { public static void main(String[] args) { MultiStoryHousemsh = new MultiStoryHouse(6, 3000, 2); MultiStoryHouse other = (MultiStoryHouse)msh.clone(); } } //Exception

  31. Get more info! • Java docs: Cloneable • http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html • Wikipedia: Clone • http://en.wikipedia.org/wiki/Clone_(28Java_method) • Clone( ) method explained! • http://geekexplains.blogspot.com/2008/06/what-is-cloning-how-clone-method-works.html

  32. Things to do: this July 4th • 32nd Annual Melon Run (3Miler) • at Westside Park, Gainesville. See Florida Track Club (FTC) website for details. • Celebration and fireworks (in Alachua) at • Hal Brady Recreation Complex(14300 NW 146th Terr.) • See “Venture outside Gainesville this July 4th” article at Gainesville.com

More Related