Interfaces and polymorphism
Download
1 / 62

Interfaces and Polymorphism - PowerPoint PPT Presentation


  • 118 Views
  • Uploaded on

Interfaces and Polymorphism. 9.1 Using Interfaces for Code Reuse 9.1.1 Defining an Interface 9.1.2 implementing an interface 9.2 Converting between Class and Interface Types 9.3 Polymorphism 9.4 Callbacks. Assignment. Read Sections 9.1-9.3 and do self check exercises 1-7.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Interfaces and Polymorphism' - paxton


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Interfaces and polymorphism

Interfaces and Polymorphism

9.1 Using Interfaces for Code Reuse

9.1.1 Defining an Interface

9.1.2 implementing an interface

9.2 Converting between Class and Interface Types

9.3 Polymorphism

9.4 Callbacks


Assignment
Assignment

  • Read Sections 9.1-9.3 and do self check exercises 1-7.

  • Read Section 9.4 and do self-check exercises 8-10.

  • Review Exercises:

    • R9.1 – R9.4, R9.6, R9.8

      • Due Tuesday, January 22, 2013

  • Programming Exercises:

    • P9.1, 9.2, and 9.4 (9.5 & 9.6)

      • Due Friday, February 1, 2013


Interface
Interface

  • A Java interface declares a set of methods and their signatures. Unlike a class, it provides no implementation.

  • To realize (implement) an interface, a class must supply all the methods that the interface requires.


  • A Java interface declares methods that classes are expected to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Contain no instance fields (cannot construct an object of an interface type)

  • Interfaces can be implemented by many classes

  • A class can implement multiple interfaces.


Uml diagram unified modeling language

<<interface>> to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

Flier

fly()

Bird

Airplane

SkiJumper

UML Diagram(Unified Modeling Language)

A Flier is one that flies.

Three dissimilar classes


Interface example
Interface Example to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

public interface Flier

{

void fly();

}

Notice – no public modifier in the method header

- Methods defined in an interface are all public by default.


Classes realizing flier
Classes realizing to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.Flier

public class Bird implements Flier

{

public void fly()

{

System.out.println("Using my wings to fly");

}

}

==================================================================

public class Airplane implements Flier

{

public void fly()

{

System.out.println("Using my jet engines to fly");

}

}

==================================================================

public class SkiJumper implements Flier, Athlete, Comparable

{

public void fly()

{

System.out.println("Using skis to take me into the air");

}

}


Creating an arraylist of fliers
Creating an ArrayList of Fliers to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

ArrayList<Flier> airborne = new ArrayList<Flier>();

airborne.add(new SkiJumper(“Jumper”, “One”));

airborne.add(new SkiJumper(“Jumper”, “Two”));

airborne.add(new Airplane());


Uml diagram

<<interface>> to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

Flier

<<interface>>

Athlete

fly()

train()

Bird

Airplane

SkiJumper

UML Diagram


Another interface
Another Interface to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

public interface Athlete

{

void train(double hours);

}

Used by SkiJumper class


Realizing the interfaces
Realizing the Interfaces to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

public class SkiJumper implements Flier, Athlete

{

//Constructor{ }

public void fly()

{

System.out.println("Using skis to take " + myFirstname + " "

+ myLastName + " into the air.");

myNumberOfJumps++;

}

public void train(double hours)

{

System.out.println("I am on the slopes " + hours + " hours today.");

myHoursTraining +=hours;

}

// more methods and private instance fields go here


Public interface comparable
public interface Comparable to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Method Summary

    • intcompareTo(Object o)

      - Used with the String class

      - Compares this object with the specified object for order (o). 

Returns:

Neg value if String less than o

0 if String equals o

Pos value if String greater than o


Example
Example to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • StringimplementsComparable

    • We can compare two strings by invoking the String method compareTo.

    • String makes a promise to "define" what is means to compare two String objects.

      String s1 = <some string>;

      String s2 = <some string>;

      if (s2.compareTo(s1))…….


Examples
Examples to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • public class Circle implements Comparable

    {

    public int compareTo(Object o)

    // Circle must define what it means to compare two Circle objects.

    }

  • If we want to compare two circles, we must supply the method compareTo.


Examples1
Examples to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • public class Circle implements Comparable

    {

    public int compareTo(Object o)

    {

    Circle c = (Circle) o;

    if (this.equals(c)) return 0;

    if (this.radius < c.radius) return -1;

    return 1;

    }

    … // we have already defined equals for Circle. What if equals is not defined for Circle?

    }


Examples2
Examples to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • public class Student implements Comparable

    {

    public int compareTo(Object o)

    {

    }

    }


Examples3
Examples to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • public class Student implements Comparable

    {

    public intcompareTo(Object o)

    {

    Student s = (Student) o;

    if (this.equals(s)) return 0;

    if (this.gpa < s.gpa) return -1;

    return 1;

    }

    }


An interface
An interface….. to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • "To be useful, an interface must be realized (implemented) by at least one Java class." – Rick Mercer

  • A class may implement MANY interfaces.


Interfaces
Interfaces to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • SHOULD NOT GROW!

    • Classes have "contracts" with an interface.

    • If the interface changes, all classes that realize the interface are affected!

  • Interfaces allow for encapsulating similar behaviors between unrelated classes.


Interface1
Interface to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Contains constants, method signatures or both.

  • NO implementations.

  • No instance variables.


Using interfaces
Using interfaces to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Define a set of methods as an interface.

    • Classes that realize the interface must support all the methods of the interface.

  • Create classes that implement those methods.

  • Compiler verifies that method calls are valid.

    (if not, the compiler will complain)


Interface declarations
Interface declarations: to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • All methods in an interface are public. The methods in the interface are not declared as public because they are public by default.

  • When implementing the methods of the interface in a class, include the keyword public.


Interfaces1
Interfaces to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Cannot be instantiated.

    • Flier f = new Flier();

    • You can use interface name as a variable type; variable can refer to an object of any class that implements the interface.

    • Flier b = new Bird();

    • Flier s = new SkiJumper();

NO

OK

OK


Using interfaces1
Using interfaces to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Interfaces define types (sets of methods).

  • A variable of type Flier must refer to an object that implements methods defined by Flier, not necessarily to an instance of Flier.

  • Actual method invoked is defined by the object’s class, at run-time. (dynamic or late binding)


Polymorphism
polymorphism… to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Late Binding: Behavior can vary depending on the actual type of an object. Occurs at runtime. The method selection takes place when the program runs.

  • Early Binding (overloading):occurs at compile time. The compiler selects a method from several possible candidates.


Polymorphism1
polymorphism to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • "In the object-oriented world, polymorphism refers to the ability of different kinds of objects to respond differently to the same commands, provided that the objects belong to classes with a common ancestor."

    K.N.King

The principle that the actual type of the object determines the method to be called is called polymorphism.

The term “polymorphism” comes from the Greek words for “many shapes.”


Again
Again… to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Early binding of methods occurs if the compiler selects a method from several possible candidates as with overloaded methods.

  • Late binding occurs if the method selection takes place when the program runs.


The importance of is a
The importance of to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.IS-A

  • You can convert from a class type to an interface type if the class realizes the interface.

    String str = "word";

    Comparable p = str; //

  • You need a cast to convert from an interface type to a class type.

    String str = "word";

    Comparable p = str;

    String t = p; //

OK

NO


The importance of is a1
The importance of to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.IS-A

  • You can convert from a class type to an interface type if the class realizes the interface.

    String str = "word";

    Comparable p = str; //

  • You need a cast to convert from an interface type to a class type.

    String str = "word";

    Comparable p = str;

    String t = (String)p; //

OK

OK


Instanceof operator
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

EXAMPLE 1

  • The instanceof operator tests whether an object belongs to a particular type. What happens?

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier instanceof SkiJumper)

    System.out.println("That's right.");

    else

    System.out.println("NOT");


Instanceof operator1
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

  • The instanceof operator tests whether an object belongs to a particular type. What happens?

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier instanceof SkiJumper)

    System.out.println("That's right.");

    else

    System.out.println("NOT");

    That's right.


Instanceof operator2
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

EXAMPLE 2

  • The instanceof operator tests whether an object belongs to a particular type. What happens?

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier instanceof Flier)

    System.out.println("That's right.");

    else

    System.out.println("NOT");


Instanceof operator3
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

  • The instanceof operator tests whether an object belongs to a particular type.

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier instanceof Flier)

    System.out.println("That's right.");

    else

    System.out.println("NOT");

    That's right.


Instanceof operator4
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

EXAMPLE 3

  • The instanceof operator tests whether an object belongs to a particular type. What happens?

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier2 instanceof Flier)

    System.out.println("That's right.");

    else

    System.out.println("NOT");


Instanceof operator5
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

  • The instanceof operator tests whether an object belongs to a particular type.

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier2 instanceof Flier)

    System.out.println("That's right.");

    else

    System.out.println("NOT");

    That's right.


Instanceof operator6
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

EXAMPLE 4

  • The instanceof operator tests whether an object belongs to a particular type. What happens?

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier2 instanceof SkiJumper)

    System.out.println("That's right.");

    else

    System.out.println("NOT");


Instanceof operator7
instanceof to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.operator

  • The instanceof operator tests whether an object belongs to a particular type.

    Flier aFlier = new SkiJumper("Joe","Smith");

    Flier aFlier2 = new Airplane();

    if (aFlier2 instanceof SkiJumper)

    System.out.println("That's right.");

    else

    System.out.println("NOT");

    NOT


Polymorphism is not overloading
Polymorphism is NOT Overloading. to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • Method signature

    • refers to method name and parameters

  • Overloading means methods have different signatures(different parameters).

    • Overloading usually occurs in same class.

    • BankAccount has two constructors. One of the constructors has one double parameter. One of the constructors has no parameters.

    • The compiler chooses the appropriate method.


Polymorphism2
Polymorphism to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar.

  • The actual type of the object determines which method is to be called.

  • This is late binding (dynamic binding).

  • The virtual machine, not the compiler, selects the appropriate method at run time.


Suppose C is a class that realizes the interfaces I and J. Which of the following assignments require a cast?

C c = …;

I i = …;

J j = …;

  • c = i;

  • j = c;

  • i = j;


Suppose C is a class that realizes the interfaces I and J. Which of the following assignments require a cast?

C c = …;

I I = …;

J j = …;

  • c = i;

  • j = c;

  • i = j;


Suppose C is a class that realizes the interfaces I and J. Which of the following assignments will throw an exception?

C c = new C();

  • I i = c;

  • J j = (J)i;

  • C d = (C)i


Suppose C is a class that realizes the interfaces I and J. Which of the following assignments will throw an exception?

C c = new C();

  • I i = c;

  • J j = (J)i;

  • C d = (C)I;

    NONE


Consider the following dataset class p 249
Consider the following Which of the following assignments will throw an exception?DataSet class.p. 249

//Computes the average of a set of

// data values.

public class DataSet

{

public DataSet()

{

sum = 0;

count = 0;

maximum = 0;

}

//Adds a data value to the data // set

public void add(double x)

{

sum = sum + x;

if (count == 0 || maximum < x)

maximum = x;

count++;

}

//Returns the average of the added data.

public double getAverage()

{

if (count == 0) return 0;

else return sum / count;

}

//Returns the largest of the added data

// or 0 if no data has been added

public double getMaximum()

{

return maximum;

}

private double sum;

private double maximum;

private int count;

}


Concerns
Concerns Which of the following assignments will throw an exception?

  • Suppose we wanted to find the BankAccount with the highest balance?

  • Suppose we wanted to find the Coin with the highest value?

  • Suppose we wanted to find the Student with the highest gpa?


Solution
Solution: Which of the following assignments will throw an exception?

BankAccount solution

//Computes the average of a set of

// data values.

public class DataSet

{

public DataSet()

{

sum = 0;

count = 0;

maximum = 0;

}

//Adds a data value to the data // set

public void add(BankAccount x)

{

sum = sum + x.getBalance();

if (count == 0

|| maximum.getBalance() < x.getBalance())

maximum = x;

count++;

}

//Returns the average of the added data.

public double getAverage()

{

if (count == 0) return 0;

else return sum / count;

}

//Returns the largest of the added data

// or 0 if no data has been added

public BankAccount getMaximum()

{

return maximum;

}

private double sum;

private BankAccount maximum;

private int count;

}


Solution1
Solution: Which of the following assignments will throw an exception?

Coin solution

//Computes the average of a set of

// data values.

public class DataSet

{

public DataSet()

{

sum = 0;

count = 0;

maximum = 0;

}

//Adds a data value to the data // set

public void add(Coin x)

{

sum = sum + x.getValue();

if (count == 0

|| maximum.getValue () < x.getValue ())

maximum = x;

count++;

}

//Returns the average of the added data.

public double getAverage()

{

if (count == 0) return 0;

else return sum / count;

}

//Returns the largest of the added data

// or 0 if no data has been added

public Coin getMaximum()

{

return maximum;

}

private double sum;

private Coin maximum;

private int count;

}


Solution2
Solution: Which of the following assignments will throw an exception?

Student solution

//Computes the average of a set of

// data values.

public class DataSet

{

public DataSet()

{

sum = 0;

count = 0;

maximum = 0;

}

//Adds a data value to the data // set

public void add(Student x)

{

sum = sum + x.getGpa();

if (count == 0

|| maximum.getGpa () < x.getGpa ())

maximum = x;

count++;

}

//Returns the average of the added data.

public double getAverage()

{

if (count == 0) return 0;

else return sum / count;

}

//Returns the largest of the added data

// or 0 if no data has been added

public StudentgetMaximum()

{

return maximum;

}

private double sum;

private Student maximum;

private int count;

}


Hmmmmm
Hmmmmm… Which of the following assignments will throw an exception?

  • Clearly the mechanics of analyzing the data is the same in ALL cases but the details of measurement are different.

    • BankAccount : balance

    • Coin: value

    • Student: gpa


Suppose we consider the following
Suppose we consider the following: Which of the following assignments will throw an exception?

public interface Measurable

{

double getMeasure();

}


Solution3
Solution: Which of the following assignments will throw an exception?

//Computes the average of a set of

// data values.

public class DataSet

{

public DataSet()

{

sum = 0;

count = 0;

maximum = 0;

}

//Adds a data value to the data // set

public void add(Measurable x)

{

sum = sum + x.getMeasure();

if (count == 0

|| maximum.getMeasure () < x.getMeasure ())

maximum = x;

count++;

}

//Returns the average of the added data.

public double getAverage()

{

if (count == 0) return 0;

else return sum / count;

}

//Returns the largest of the added data

// or 0 if no data has been added

public Measurable getMaximum()

{

return maximum;

}

private double sum;

private Measurable maximum;

private int count;

}


And… Which of the following assignments will throw an exception?

public class BankAccount implements Measurable{

. . . . .

public double getMeasure()

{

return balance;

}


Test class
Test class Which of the following assignments will throw an exception?

public class DataSetTest

{

public static void main(String[] args)

{

DataSet bankData = new DataSet();

bankData.add(new BankAccount(0));

bankData.add(new BankAccount(10000));

bankData.add(new BankAccount(2000));

System.out.println("Average balance = " + bankData.getAverage());

Measurable max = bankData.getMaximum();

System.out.println("Highest balance = " + max.getMeasure());

DataSet coinData = new DataSet();

coinData.add(new Coin(0.25, "quarter"));

coinData.add(new Coin(0.1, "dime"));

coinData.add(new Coin(0.05, "nickel"));

System.out.println("Average coin value = " + coinData.getAverage());

max = coinData.getMaximum();

String name = ((Coin)max).getName();

System.out.println(name + " has the highest coin value of " + max.getMeasure());

}

}


And… Which of the following assignments will throw an exception?

public class Coin implements Measurable{

. . . . .

public double getMeasure()

{

return value;

}


And… Which of the following assignments will throw an exception?

public class Student implements Measurable{

. . . . .

public double getMeasure()

{

return gpa;

}


Using interfaces for callbacks
Using Interfaces for Callbacks Which of the following assignments will throw an exception?

  • Limitations of Measurable interface:

    • Can add Measurable interface only to classes under your control

    • Can measure an object in only one way E.g., cannot analyze a set of savings accounts both by bank balance and by interest rate

  • Callback mechanism: allows a class to call back a specific method when it needs more information

  • In previous DataSet implementation, responsibility of measuring lies with the added objects themselves


Using interfaces for callbacks cont
Using Interfaces for Callbacks (cont.) Which of the following assignments will throw an exception?

  • Alternative: Hand the object to be measured to a method:public interface Measurer { double measure(Object anObject); }

  • Object is the "lowest common denominator" of all classes


Using interfaces for callbacks1
Using Interfaces for Callbacks Which of the following assignments will throw an exception?

  • add method asks measurer (and not the added object) to do the measuring: public void add(Object x) { sum = sum + measurer.measure(x); if (count == 0 || measurer.measure(maximum) < measurer.measure(x)) maximum = x; count++;


Using interfaces for callbacks2
Using Interfaces for Callbacks Which of the following assignments will throw an exception?

  • You can define measurers to take on any kind of measurement public class RectangleMeasurer implements Measurer { public double measure(Object anObject) { Rectangle aRectangle = (Rectangle) anObject; double area = aRectangle.getWidth() * aRectangle.getHeight();

  • Must cast from Object to RectangleRectangleaRectangle = (Rectangle) anObject;


Using interfaces for callbacks cont1
Using Interfaces for Callbacks (cont.) Which of the following assignments will throw an exception?

  • Pass measurer to data set constructor: Measurer m = new RectangleMeasurer(); DataSet data = new DataSet(m); data.add(new Rectangle(5, 10, 20, 30)); data.add(new Rectangle(10, 20, 30, 40)); . . .


UML Diagram of Which of the following assignments will throw an exception?Measurer Interface and Related Classes

Note that the Rectangle class is decoupled from the Measurer interface


Assignment1
Assignment Which of the following assignments will throw an exception?

  • Read Sections 9.1-9.3 and do self check exercises 1-7.

  • Read Section 9.4 and do self-check exercises 8-10.

  • Review Exercises:

    • R9.1 – R9.4, R9.6, R9.8

      • Due Tuesday, January 22, 2013

  • Programming Exercises:

    • P9.1, 9.2, and 9.4 (9.5 & 9.6)

      • Due Friday, February 1, 2013


ad