CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Interfaces (Part II) Course Lecture Slides 28 June 2010 “A picture is.

Slides:



Advertisements
Similar presentations
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Interfaces (Part II) Course Lecture Slides 28 June 2010 A picture is.
Advertisements

 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Java Programming Abstract classes and Interfaces.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Mutable, Immutable, and Cloneable Objects Chapter 15.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 10 Abstract Classes.
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.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
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.
Mutable, Immutable, and Cloneable Objects Chapter 15 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Programming 2 LAB TA: Nouf Al-Harbi NoufNaief.net :::
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 1 Introduction to Computers,
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 1 Chapter 13 Abstract Classes and Interfaces.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
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 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 10 Abstract Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Abstract Classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 1 Chapter 13 Abstract Classes and Interfaces.
Interfaces and Inner Classes
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
ABSTRACT DATA TYPES, ABSTRACT CLASSES AND INTERFACES And abstract art….
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Abstract Classes and Interfaces.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Abstract Classes and Interfaces.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 11 Abstract Classes.
CS 112 Programming 2 Lecture 10 Abstract Classes & Interfaces (1)
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Interfaces Are used to model weak inheritance relationships Object-inheritance.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Chapter 15 Abstract Classes and Interfaces.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
1 Chapter 5 Abstract Classes and Interfaces. 2 Objectives u To design and use abstract classes. u To process a calendar using the Calendar and GregorianCalendar.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
1 1 Chapter 14 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code.
Chapter 13 Abstract Classes and Interfaces
Chapter 13 Abstract Classes and Interfaces
Chapter 7: Cloning and RTTI
Abstract Classes and Interfaces in Java Reference: COS240 Syllabus
Chapter 11 Abstract Classes and Interfaces
Java and OOP Part 5 – More.
IST311 / 602 Cleveland State University – Prof. Victor Matos
Chapter 8 Classes and Objects
Chapter 13 Abstract Classes and Interfaces
CIS3023: Programming Fundamentals for CIS Majors II
CSE 331 Cloning objects slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Chapter 12 Abstract Classes and Interfaces
Interfaces.
IST311 / 602 Cleveland State University – Prof. Victor Matos
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chapter 13 Abstract Classes and Interfaces Part 01
Presentation transcript:

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

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

Comparable Interface // Interface defined in java.lang package public interface Comparable { public int compareTo(Object o); } 3 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: ClassCastException if the specified object's type prevents it from being compared to this Object.ClassCastException

Declaring Classes to Implement Comparable 4

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 int compareTo(Object o) { ComparableRectangle cr = (ComparableRectangle)o; if (getArea() > cr.getArea()) return 1; else if(getArea() < cr.getArea()) return -1; else return 0; }

Using Arrays.sort() If you have an array of objects of some class C and you want to use Arrays.sort(Object[] a)Object or Arrays.sort(Object[] a, int fromIndex, int toIndex)Object 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 6

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)ObjectComparator Or Arrays.sort(Object[] a, int fromIndex, int toIndex, Comparator c)ObjectComparator 7

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

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

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 10

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

Another Advantage of using interfaces as data types 12 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));

Another Advantage of using interfaces as data types 13 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));

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

Get more info! Tutorial: Comparable vs. Comparator: Using comparable: 15

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.

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

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

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 references to 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.

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.

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:as follows package java.lang; public interface Cloneable { }

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

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

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.Date whenBuilt; 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(); } }

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

public class House implements Cloneable{ private int id; private double area; private java.util.Date whenBuilt; // 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.

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?

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

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

Get more info! Java docs: Cloneable Wikipedia: Clone Clone( ) method explained! 31

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