0% found this document useful (0 votes)
9 views41 pages

Week12 - Interfaces and Polymorphism FL24 2

Uploaded by

turkyalmuz90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views41 pages

Week12 - Interfaces and Polymorphism FL24 2

Uploaded by

turkyalmuz90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

COMP2202

Fundamentals of Object Oriented


Programming
Interfaces and Polymorphism

1
Lecture Goals

 To be able to declare and use abstract classes


 To be able to declare and use interface types
 To appreciate how interfaces can be used to decouple
classes
 To learn how to implement helper classes as inner
classes
 To understand the concept of polymorphism
Copyright © 2014 by John Wiley & Sons. All rights
2
reserved.
Java Class Types
 In Java, classes maybe of different types.
 So far we discussed only one type, the
concrete class; a class that has implemented
all its methods.
 In this lecture, we’ll introduce two other types
of class: Abstract class and Interface.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 3
Using an Abstract Classes
 Sometimes there is no good default for the
superclass method and only the subclass
programmer can know how to implement the
method properly.
 Solutions
• We could define an empty superclass method but
then first it’s useless and the subclass programmer
may forget to implement it.
• Instead, the programmer will be forced to redefine
the method by declaring it abstract.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 4
Abstraction in OOP

Copyright © 2014 by John Wiley & Sons. All rights reserved. 6


Using an Abstract Class
 Example:
public abstract class BankAccount
{
public abstract void deductFees();

}
public SavingAccount implements BankAccount
{

public void deductFees(){

}
}
BankAccount myAccount; //Allowed
BankAccount myAccount=new BankAccount();//Error
myAccount = new SavingAccount();//Allowed
myAccount=null;//Allowed

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 7
Using Interfaces for Algorithm Reuse

 Interfaces make it possible to make a service available


to a wide set of inputs by focusing on the essential
operations that the service requires.
 Interface types are used to express these common
operations.
 This restaurant is willing to serve anyone who conforms
to the Customer interface with eat and pay methods.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 8
Defining an Interface Type
 Example: a method to compute the average of an array
of Objects
• The algorithm for computing the average is the same in all
cases
• Details of measurement differ
 Example:
• Compute average of bank balance
• Compute average of countries’ area

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 9
Defining an Interface Type
• Compute average of bank balance  getBalance()
• Compute average of countries’ area  getArea()
• Compute average of Employees’ salary  getSalary()
• Compute average of Students’ scores  getScore()
• Compute average of Products’ prices  getPrice()

Same algorithm of
computing average but
with different
measurements

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 10
Defining an Interface Type
 Goal: write one method that provides this service.
 We can't call getBalance in one case and getArea in
another.

Remember all of
type Object

Use getMeasure()

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 11
Defining an Interface Type
 Solution: all object who want this service must agree on
a getMeasure method
• BankAccount's getMeasure will return the balance
• Country's getMeasure will return the area
 Now we implement a single average method that
computes the sum:
sum = sum + obj.getMeasure();

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 12
Defining an Interface Type
 Problem: we need to declare a type for obj

 Need to invent a new type that describes any class whose


objects can be measured.
 An interface type is used to specify required operations (like
getMeasure):
public interface Measurable
{
double getMeasure(); //no need to add public
// all interface methods
// are automatically public
}

 A Java interface type declares methods but does not provide


their implementations.
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 13
Declaring an Interface

Copyright © 2014 by John Wiley & Sons. All rights reserved. 14


Defining an Interface Type
 An interface type is similar to a class.
 Differences between classes and interfaces:
• An interface type does not have instance variables.
• All methods in an interface type are abstract
o They have a name, parameters, and a return type, but no
implementation.

• All methods in an interface type are automatically public.


• An interface type has no constructor.
o You cannot construct objects of an interface type.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 15
Defining an Interface Type
 Implementing a reusable average method:
public static double average(Measurable[] objects)
{
double sum = 0;
for (Measurable obj : objects)
{
sum = sum + obj.getMeasure();
}
if (objects.length > 0) { return sum / objects.length; }
else { return 0; }
}

 This method can be used for objects of any

class that conforms to the Measurable type.


Copyright © 2014 by John Wiley & Sons. All rights
reserved. 16
Implementing an Interface Type
 Use implements reserved word to indicate that a class
implements an interface type:
public class BankAccount implements Measurable
{

public double getMeasure() // the class must declare the
{ // method
as public, whereas
return balance; // the interface need not
}
}

 BankAccount objects are instances of the Measurable type:


Measurable obj = new BankAccount(); // OK
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 17
Implementing an Interface

Copyright © 2014 by John Wiley & Sons. All rights reserved. 18


Implementing an Interface Type
 A variable of type Measurable holds a reference to an object
of some class that implements the Measurable interface.
 Country class can also implement the Measurable interface:
public class Country implements Measurable
{
public double getMeasure()
{
return area;
}
...
}

 Use interface types to make code more reusable.


Copyright © 2014 by John Wiley & Sons. All rights
reserved. 19
Implementing an Interface Type
 Put the average method in a class - say Data

Figure 1 UML Diagram of the Data Class and the Classes that Implement the
Measurable Interface
 Data class
In the UML is decoupled
notation, (separated
interfaces are tagged ) from
with an indicator the
«interface». A dotted
BankAccount and
arrow with a triangular tip ( Country
) denotesclasses.
the implements relationship between a class
and an interface. You have to look carefully at the arrow tips—a dotted line with an
open arrow tip ( ) denotes the uses relationship or dependency.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 20
section_1/Data.java
1 public class Data
2 {
3 /**
4 Computes the average of the measures of the given objects.
5 @param objects an array of Measurable objects
6 @return the average of the measures
7 */
8 public static double average(Measurable[] objects)
9 {
10 double sum = 0;
11 for (Measurable obj : objects)
12 {
13 sum = sum + obj.getMeasure();
14 }
15 if (objects.length > 0) { return sum / objects.length; }
16 else { return 0; }
17 }
18 }

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 21
section_1/MeasurableTester.java
1 /**
2 This program demonstrates the measurable BankAccount and Country classes.
3 */
4 public class MeasurableTester
5 {
6 public static void main(String[] args)
7 {
8 Measurable[] accounts = new Measurable[3];
9 accounts[0] = new BankAccount(0);
10 accounts[1] = new BankAccount(10000);
11 accounts[2] = new BankAccount(2000);
12
13 double averageBalance = Data.average(accounts);
14 System.out.println("Average balance: " + averageBalance);
15 System.out.println("Expected: 4000");
16
17 Measurable[] countries = new Measurable[3];
18 countries[0] = new Country("Uruguay", 176220);
19 countries[1] = new Country("Thailand", 513120);
20 countries[2] = new Country("Belgium", 30510);
21
22 double averageArea = Data.average(countries);
23 System.out.println("Average area: " + averageArea);
24 System.out.println("Expected: 239950");
25 }
Continued
26 }
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 22
section_1/MeasurableTester.java
Program Run:

Average balance: 4000


Expected: 4000
Average area: 239950
Expected: 239950

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 23
Comparing Interfaces and Inheritance
 Here is a different interface: Named
public interface Named
{ Inheritance:
String getName();
}  A class can only extend (inherit
 A class can implement more than one from) a single superclass.
interface:
public class Country implements Measurable,
 A superclass provides some
Named
implementation that a subclass
inherits.
 An interface specifies the behavior that an
implementing class should supply - no
implementation.
 Develop interfaces when you have code
that processes objects of different classes
in a common way.
 For example, a traffic simulation might
model the movement of people, cars, dogs,
balls, and so on. In this example, you
might create a Moveable interface with
methods
Copyright move
© 2014 by John Wileyand getPosition.
& Sons. All rights
reserved. 25
Common Errors

Copyright © 2014 by John Wiley & Sons. All rights reserved. 26


Converting From Classes to Interfaces
 You can convert from a class type to an interface type, provided
the class implements the interface.
 A Measurable variable can refer to an object of the BankAccount
class because BankAccount implements the Measurable interface:
BankAccount account = new BankAccount(1000);
Measurable meas = account; // OK

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 27
Converting From Classes to Interfaces
 A Measurable variable can refer to an object of the
Country class because that class also implements the
Measurable interface:
Country uruguay = new Country("Uruguay", 176220);
Measurable meas = uruguay; // Also OK

 A Measurable variable cannot refer to an object of the


Rectangle class because Rectangle doesn't implement
Measurable:
Measurable meas = new Rectangle(5, 10, 20, 30); // ERROR

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 28
Casting from Interfaces to Classes
 Method to return the object with the largest measure:
public static Measurable larger(Measurable obj1, Measurable obj2)
{
if (obj1.getMeasure() > obj2.getMeasure())
{
return obj1;
}
else
{
return obj2;
}
}

 Returns the object with the larger measure, as a Measurable reference.


Country uruguay = new Country("Uruguay", 176220);
Country thailand = new Country("Thailand", 513120);
Measurable max = larger(uruguay, thailand);
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 29
Casting from Interfaces to Classes
 You know that max refers to a Country object, but the compiler
does not.
String countryName = max.getName(); //Error

 Solution: cast
Country maxCountry = (Country) max;
String name = maxCountry.getName();

 You need a cast to convert from an interface type to a class


type.
 If you are wrong and max doesn't refer to a Country object, the
program throws an exception at runtime.
 If a Person object is actually a Superhero, you need a cast

before you can apply any Superhero methods.


Copyright © 2014 by John Wiley & Sons. All rights
reserved. 30
Polymorphism with inheritance
 Polymorphism means “having multiple forms”
 When the virtual machine calls an instance method -
• It locates the method of the implicit parameter’s class.
• This is called dynamic method lookup
 Dynamic method lookup allows us to treat objects of
different classes in a uniform way.
 This feature is called polymorphism. It allows us to
manipulate objects that share a set of tasks, even
though the tasks are executed in different ways.
 We ask multiple objects to carry out a task, and each
object does so in its own way.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 31
Polymorphism with inheritance
 Problem:
We want to use the same method (presentQuestion())
to display the question and check whether the user
supplied the correct answer for both types of questions:
Question and ChoiceQuestion

 The Question superclass has a method for displaying


and checking.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 32
Polymorphism with inheritance
 We can simply declare the parameter variable of the
presentQuestion method to have the type Question:
public static void presentQuestion(Question q)
{
q.display();
System.out.print("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
 We can substitute a subclass object whenever a
superclass object is expected:
ChoiceQuestion second = new ChoiceQuestion();
FillInQuestion third = new FillInQuestion();
Quesiton q1 = new Question(); presentQuestion(q1);
presentQuestion(second);
presentQuestion(third);
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 33
Polymorphism with inheritance
 When the presentQuestion method executes –
• The object references stored in second and q refer to the same
object
• The object is of type ChoiceQuestion

Figure 7 Variables of Different Types Referring to the Same Object

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 34
Polymorphism with inheritance
 The variable q knows less than the full story about the
object to which it refers.

Figure : A Question Reference Can Refer to an Object of Any Subclass of Question

 In the same way that vehicles can differ in their method


of movement/drive, polymorphic objects carry out tasks
in different ways.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 35
QuestionDemo3.java
1 import java.util.Scanner;
2 /* This program shows a simple quiz with two question types. */
6 public class QuestionDemo3
7 { public static void main(String[] args)
9 { Question first = new Question(); //superclass
11 first.setText("Who was the inventor of Java?");
12 first.setAnswer("James Gosling");
13 ChoiceQuestion second = new ChoiceQuestion(); //subclass
15 second.setText("In which country was the inventor of Java born?");
16 second.addChoice("Australia", false);
17 second.addChoice("Canada", true);
18 second.addChoice("Denmark", false);
19 second.addChoice("United States", false);
20
21 presentQuestion(first); //call by passing superclass object
22 presentQuestion(second);//call by passing subclass object
23 }//end of QuestionDemo3
25 /* Presents a question to the user and checks the response.
27 @param q the question */
29 public static void presentQuestion(Question q)
30 { q.display();
32 System.out.print("Your answer: ");
33 Scanner in = new Scanner(System.in);
34 String response = in.nextLine();
35 System.out.println(q.checkAnswer(response));
36 }
37 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
QuestionDemo3.java
Program Run:
Who was the inventor of Java?
Your answer: Bjarne Stroustrup
False
In which country was the inventor of Java born?
1: Australia
2: Canada
3: Denmark
4: United States
Your answer: 2
True

Student std1=new Student();


Student std2=new Student(“s123”,”Ahmed”,”SCI”);

Copyright © 2014 by John Wiley & Sons. All rights reserved. 37


Polymorphism with Interfaces
 Multiple classes implement the same interface, but method
implementation differs.
 Common to have variables of type interface; but no object of type
interface:
Measurable meas;

 Objects of type class that implements the interface:


meas = new BankAccount(1000); //OK

meas = new Country(“Thailand”, 513120); //OK

 An interface variable allows to invoke methods of the interface.


double m = meas.getMeasure( );

 Polymorphism concept used:


 Data class able to compute measure of added objects without knowing
the kind of object was added
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 38
Polymorphism
 When meas.getMeasure( ); is called, it belongs to
which class BankAccount or Country???
 The dynamic method lookup mechanism allows the Java
virtual machine to locate the correct method by first
looking at the class of the actual object, and then
calling the method with the given name in that class.
• If meas refers to BankAccount object, then the
BankAccount.getMeasure method is called.
• If meas refers to Country object, then the Country.getMeasure
method is called.
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 39
Variables of Class and Interface Types

Figure 3 An Interface Reference Can Refer to an Object of Any Class that


Implements the Interface

 Method calls on an interface reference are polymorphic.


The appropriate method is determined at run time.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 40


The Comparable Interface
 Comparable interface of the standard Java library.
 Comparable interface has a single method:
public interface Comparable
{
int compareTo(Object otherObject);
}

 The call to the method:


a.compareTo(b)

 The compareTo method returns:


• a negative number if a should come before b,

• zero if a and b are the same

• a positive number if b should come before a.

 Implement the Comparable interface so that objects of your class can be


compared,
Copyright © 2014 by Johnfor
Wileyexample,
& Sons. All rightsin a sort method.
reserved. 41
The Comparable Interface
 BankAccount class’s implementation of Comparable:
public class BankAccount implements Comparable
{
...
public int compareTo(Object otherObject)
{
BankAccount other = (BankAccount) otherObject;
if (balance < other.balance) { return -1; }
if (balance > other.balance) { return 1; }
return 0;
}
...
}

 compareTo method has a parameter of reference type Object

 To get a BankAccount reference: //use casting


BankAccount other = (BankAccount) otherObject;
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 42
The Comparable Interface
 Because the BankAccount class implements the
Comparable interface, you can sort an array of bank
accounts with the Arrays.sort method:
BankAccount[] accounts = new BankAccount[3];
accounts[0] = new BankAccount(10000);
accounts[1] = new BankAccount(0);
accounts[2] = new BankAccount(2000);
Arrays.sort(accounts);

 Now the accounts array is sorted by increasing balance.


 The compareTo method checks whether
another object is larger or smaller.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 43

You might also like