0% found this document useful (0 votes)
83 views31 pages

CSE201: Monsoon 2018, CSE Sec1on Advanced Programming: Lecture 05: Interfaces and Polymorphism

lec 5

Uploaded by

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

CSE201: Monsoon 2018, CSE Sec1on Advanced Programming: Lecture 05: Interfaces and Polymorphism

lec 5

Uploaded by

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

CSE201: Monsoon 2018, CSE Sec1on

Advanced Programming
Lecture 05: Interfaces and
Polymorphism
Vivek Kumar
Computer Science and Engineering
IIIT Delhi
[email protected]
Last Lecture Interfaces in Java
●  Group similar capabilities/function of different
classes together
●  Interfaces can only declare methods - not define
them
●  Interfaces are contracts that classes agree to
●  If classes choose to implement given interface, it
must define all methods declared in interface
o  if classes don’t implement one of interface’s
methods, the compiler raises error
Do we need two
different Racer classes??
Declaring an Interface Implementing an Interface
Any
similarities?
How about one Racer class with different methods?

@Override is an
@Override
annota2on – a signal to
the compiler (and to
anyone reading your
code)
This Lecture

●  Interfaces and Polymorphism

Slide acknowledgements: CS15, Brown University


Back to the Race
●  Let’s make transportation classes use an interface
public class Car implements Transporter{ public class Bike implements Transporter{

public Car() { public Bike() {
//code elided //code elided
} }
public void drive(){ public void pedal(){
//code elided //code elided
} }
@Override @Override
public void move() { public void move() {
this.drive(); this.pedal();
} }
//more methods elided
} //more methods elided
}
3
Andries van Dam © 2016 9/22/16
Leveraging Interfaces
●  Given that there’s guarantee anything that implements
Transporter knows how to move, how can it be
leveraged to create single useTransportation()
method?
Racer
Racer
useCar(Car car) useTransportation()
useBike(Bike bike)
useHoverBoard(HoverBoard hoverboard)
useHorse(Horse horse)
useScooter(Scooter scooter)
useMotorcycle(Motorcycle motorcycle)
usePogoStick(PogoStick pogo)

4
Andries van Dam © 2016 9/22/16
Introducing Polymorphism
●  Poly = many, morph = forms
●  A way of coding generically
o  way of referencing many related objects as one generic type
§  cars and bikes can both move() → refer to them as Transporter
objects
§  phones and camera can both getCharged() → refer to them as
Chargeable objects, i.e., objects that implement Chargeable interface
§  cars and mobile phones can both playRadio() → refer to them as
RadioPlayer objects
●  How do we write one generic useTransportation()
method?

5
Andries van Dam © 2016 9/22/16
What would this look like in code?
public class Racer {

//previous code elided
public void useTransportation(Transporter transportation) {
transportation.move();
}

}
This is polymorphism!
transportation object passed
in could be instance of Car,
Bike, etc., i.e., any class that
implements the interface
6
Andries van Dam © 2016 9/22/16
Let’s break this down.
public class Racer {

//previous code elided
public void useTransportation(Transporter transportation) {
transportation.move();
}

}

1.  Actual vs. Declared Type


2.  Method resolution

7
Andries van Dam © 2016 9/22/16
Actual vs. Declared Type (1/2)
●  Consider following piece of code:

Transporter dansCar = new Car();



●  ...is that legal?
o  doesn’t Java do strict type checking? (type on LHS = type on RHS)
o  how can instances of Car get stored in Transporter variable?

8
Andries van Dam © 2016 9/22/16
Actual vs. Declared Type (2/2)
●  Can treat Car/Bike object as
Transporter objects
●  Car is the actual type
o  Java will look in this class for the Transporter transportation = new Car();
definition of the method transportation.playRadio();
●  Transporter is declared type
o  Java will limit caller so it can only call
methods on instances that are
declared as Transporter objects
●  If Car defines playRadio()
method. Is Nope. The playRadio() method
is not declared in Transporter
transportation.playRadio() interface, therefore Java does not
correct? recognize it as viable method call
9
Andries van Dam © 2016 9/22/16
Determining the Declared Type
●  What methods do Car and Bike Bike implements Transporter
have in common? void move();
void dropKickstand();//etc.
o  move()
●  How do we know that?
o  they implement Transporter Car implements Transporter
§  guarantees that they have move() void move();
method void playRadio();//etc.
●  Think of Transporter like the
“lowest common denominator”
o  it’s what all transportation classes
will have in common
10
Andries van Dam © 2016 9/22/16
Is this legal?
Transporter sophiasBike = new Bike();

Transporter sophiasCar = new Car();

Transporter sophiasRadio = new Radio();

Radio wouldn’t implement Transporter. Since


Radio cannot “act as” a Transporter, you
cannot treat it as Transporter.

11
Andries van Dam © 2016 9/22/16
Motivations for Polymorphism
●  Many different kinds of transportation but only care about
their shared capability
o  i.e. how they move
●  Polymorphism let programmers sacrifice specificity for
generality
o  treat any number of classes as their lowest common denominator
o  limited to methods declared in that denominator
§  can only use methods declared in Transporter
●  For this program, that sacrifice is ok!
o  Racer doesn’t care if instance of Car can playRadio() or if instance of Bike
can dropKickstand()
o  only method Racer wants to call is move() 12
Andries van Dam © 2016 9/22/16
Polymorphism in Parameters
●  What are implications of this method declaration?

public void useTransportation(Transporter transportation) {


//code elided
}

●  useTransportation will accept any object that implements Transporter


●  useTransportation can only call methods declared in Transporter

13
Andries van Dam © 2016 9/22/16
Is this legal?
Transporter sophiasBike = new Bike();
_sophia.useTransportation(sophiasBike); Even though
sophiasCar is
Car sophiasCar = new Car(); declared as a Car,
the compiler can still
_sophia.useTransportation(sophiasCar); verify that it
implements
Radio sophiasRadio = new Radio(); Transporter.
_sophia.useTransportation(sophiasRadio);

A Radio wouldn’t implement Transporter.


Therefore, useTransportation() cannot treat
it like a Transporter object.
14
Andries van Dam © 2016 9/22/16
Why move()? (1/2)
●  Why call move()?
●  What move() method gets executed?

public class Racer {



//previous code elided
public void useTransportation(Transporter transportation) {
transportation.move();
}

}
15
Andries van Dam © 2016 9/22/16
Why move()? (2/2)
●  Only have access to Transporter object
o  cannot call transportation.drive()or
transportation.pedal()
§  that’s okay, because all that’s needed is move()
o  limited to the methods declared in Transporter

16
Andries van Dam © 2016 9/22/16
Method Resolution: Which move() is executed?
●  Consider this line of code in Race class:
_sophia.useTransportation(new Bike());

●  Remember what useTransportation method looked like

public void useTransportation(Transporter transportation) {


transportation.move();
}

What is “actual type” of transportation in this method invocation?


17
Andries van Dam © 2016 9/22/16
Method Resolution (1/4)
public class Race {
●  Bike is actual type
private Racer_sophia;
//previous code elided
o  Racer was handed instance of
Bike
public void startRace() { §  new Bike() is argument
_sophia.useTransportation(new Bike());
} ●  Transporter is declared type
} o  Racer treats Bike object as
public class Racer {
Transporter object
//previous code elided

●  So… what happens in
public void useTransportation(Transporter transportation.move()?
transportation) { o  What move() method gets
transportation.move(); used?
}

} 18
Andries van Dam © 2016 9/22/16
Method Resolution (2/4)
public class Race {
//previous code elided
public void startRace() {
●  _Sophia is a Racer
_sophia.useTransportation(new Bike()); ●  Bike’s move() method gets
} used
}
public class Racer { ●  Why?
//previous code elided o  Bike is actual type
public void useTransportation(Transporter §  Java will execute methods
transportation) { defined in Bike class
transportation.move(); o  Transporter is declared
} type
}
§  Java limits methods that
public class Bike implements Transporter { can be called to those
//previous code elided declared in Transporter
public void move() { interface
this.pedal();
} 19
} Andries van Dam © 2016 9/22/16
Method Resolution (3/4)
●  What if _sophia received instance of Car?
o  What move() method would get called then?
§  Car’s!

public class Race {



//previous code elided

public void startRace() {
_sophia.useTransportation(new Car());
}
}
20
Andries van Dam © 2016 9/22/16
Method Resolution (4/4)
●  This method resolution is example of dynamic binding,
which is when actual method implementation used is not
determined until runtime
o  contrast with static binding, in which method gets resolved at
compile time
●  move()method is bound dynamically – Java does not
know which move() method to use until program runs
o  same “transport.move()” line of code could be executed
indefinite number of times with different method resolution each
time

21
Andries van Dam © 2016 9/22/16
Clicker Question
Given the following class:
public class Laptop implements Typeable, Clickable {
public void type() {
// code elided
}
public void click() {
//code elided
}

Given
that typeable has declared the type method and clickable has declared
the click method, which of the following calls is/are valid?

A. Typeable macBook= new Typeable(); C. Typable macBook= new Laptop();


macBook.type(); macBook.click();

Clickable macBook = new Clickable();


B. macBook.type(); D. Clickable macBook = new Laptop();
macBook.click();
22
Andries van Dam © 2016 9/22/16
Why does that work? (1/2)
●  Declared type and actual type work together
o  declared type keeps things generic
§  can reference a lot of objects using one generic type
o  actual type ensures specificity
§  when defining implementing class, the methods can get implemented
in any way
Car Actual
This is my
Transporter object!

Declared

23
Andries van Dam © 2016 9/22/16
Why does that work? (2/2)
●  Declared type and actual type work together
o  declared type keeps things generic
§  can reference a lot of objects using one generic type
o  actual type ensures specificity
§  when defining implementing class, the methods can get implemented
in any way
Bike Actual
This is my
Transporter object!

Declared

24
Andries van Dam © 2016 9/22/16
When to use polymorphism?
●  Using only functionality declared in interface or specialized
functionality from implementing class?
o  if only using functionality from the interface à polymorphism!
o  if need specialized methods from implementing class, don’t use
polymorphism

25
Andries van Dam © 2016 9/22/16
Why use interfaces?
●  Contractual enforcement
o  will guarantee that class has certain capabilities
§  Car implements Transporter, therefore it must know how to move()
●  Polymorphism
o  Can have implementation-agnostic classes and methods
§  know that these capability exists, don’t care how they’re implemented
§  allows for more generic programming
•  useTransportation can take in any Transporter object
•  can easily extend this program to use any form of transportation, with
minimal changes to existing code
§  an extremely powerful tool for extensible programming

26
Andries van Dam © 2016 9/22/16
Why is this important?
●  With 2 modes of transportation!
●  Old Design:
o  need more classes à more specialized methods
(useRollerblades(), useBike(), etc)
●  New Design:
o  as long as the new classes implement Transporter, Racer
doesn’t care what transportation it has been given
o  don’t need to change Racer!
§  less work for you!
§  just add more transportation classes that implement Transporter
27
Andries van Dam © 2016 9/22/16
public class Racer {

The Program public Racer() {}



public void useTransportation(Transporter transport){
public class App { transport.move();
public App() { }
Race r = new Race(); }
r.startRace();
public class Car implements Transporter {
}
public Car() {}
}
public void drive() {
public class Race { //code elided
private Racer _dan, _sophia; }
public void move() {
public Race(){ this.drive();
_dan = new Racer(); }
_sophia = new Racer(); }
}
public class Bike implements Transporter {
public void startRace() {
public Bike() {}
_dan.useTransportation(new Car());
public void pedal() {
_sophia.useTransportation(new Bike());
//code elided
}
}
}
public void move() {
public interface Transporter { this.pedal();
public void move(); }
} } 28
Andries van Dam © 2016 9/22/16
In Summary
●  Interfaces are contracts
o  force classes to define certain methods
●  Polymorphism allows for extremely generic code
o  treats multiple classes as their “generic type” while still allowing
specific method implementations to be executed
●  Polymorphism + Interfaces
o  generic coding
●  Why is it helpful?
o  want you to be the laziest (but cleanest) programmer you can be

29
Andries van Dam © 2016 9/22/16
Next Lecture
●  Inheritance and polymorphism

30

You might also like