Deeper Into PolymorphismJ8 Home « Deeper Into Polymorphism
So we have found a way to get around multiple inheritance by using interfaces but what are we really getting from this? The interfaces don't contain any implementation code as they are purely abstract and we have to implement them in the first concrete subclass. The answer is polymorphism! We can pass a polymorphic interface type as an argument and return a polymorphic interface type as well. A slideshow is in order to set up the scenario:
We are going to make the Plane
superclass and PassengerPlane
subclass nice and simple and we won't bother with the MilitaryPlane
code as it doesn't add to the objective:
package info.java8;
/*
A Plane class
*/
public class Plane {
}
/*
A PassengerPlane class
*/
public class PassengerPlane extends Plane implements PublicTransport {
/*
Our queue() implementation
*/
public void queue(int people) {
System.out.println("There are " + people + " people waiting to board this plane.");
}
/*
Our payFare() implementation
*/
public void payFare(int fare) {
System.out.println("This plane journey will cost you " + fare + " pounds.");
}
}
/*
Test class for PassengerPlane
*/
public class TestPassengerPlane {
public static void main (String[] args) {
PassengerPlane plane = new PassengerPlane();
plane.queue(152);
plane.payFare(502);
}
}
Save and compile the Plane
, PassengerPlane
and TestPassengerPlane
classes and then run the TestPassengerPlane
class in directory c:\_OOConcepts in the usual way.
Polymorphic Interface Arguments Top
Ok, we have seen how easy it is to implement interfaces in multiple hierarchies but what about the polymorphism? Well because the implementations can come from different hierarchies we can use the interface type as the reference type when creating our objects. As we know, an implemented abstract type is exactly the same as an overridden method type and so will use polymorphic method invocation to dynamically invoke the method of the the actual object type at runtime. This means we can group together objects from different hierarchies under the umbrella of the interface type as the reference type knowing the correct object will be always be invoked at runtime. Now we are ready to see polymorphic interface arguments in action and for this we need a couple of new classes:
package info.java8;
/*
A Carrier class
*/
public class Carrier {
private int people;
private int cost;
Carrier(int people, int cost) {
this.people = people;
this.cost = cost;
}
public void travelInfo (PublicTransport pt) {
pt.queue(people);
pt.payFare(cost);
}
}
/*
Test class for polymorphic interface arguments
*/
public class TestPolyIntArgs {
public static void main (String[] args) {
PublicTransport bus = new Bus();
PublicTransport taxi = new Taxi();
PublicTransport pp = new PassengerPlane();
Carrier carrier = new Carrier(10, 2);
carrier.travelInfo(bus);
Carrier carrier2 = new Carrier(4, 8);
carrier2.travelInfo(taxi);
Carrier carrier3 = new Carrier(162, 720);
carrier3.travelInfo(pp);
}
}
In the code above for the Carrier
class we are using the PublicTransport
interface type in our parameter lists for the methods in the class. In the TestPolyIntArgs
test class we are
passing across the argument types polymorphically using the PublicTransport
reference type. Save and compile the Carrier
and TestPolyIntArgs
classes and then run the
TestPolyIntArgs
class in directory c:\_OOConcepts in the usual way.
We are passing across objects from totally different hierarchies using the PublicTransport
interface type as the reference type. The JVM
uses polymorphic method
invocation to dynamically invoke the correct queue()
and payFare()
methods based on the actual object type within the Carrier
class methods at runtime.
Polymorphic Interface Return Types Top
We can also return objects from methods using the interface type as the reference type, safe in the knowledge that the correct method will be invoked on the actual object at runtime.
package info.java8;
/*
Test class for Polymorphic Interface Type Return
*/
public class PolymorphicIntReturn {
public static void main (String[] args) {
// Array declaration below is creating an Array object so can use interface supertype
PublicTransport[] pt = new PublicTransport[3];
for (int i=0; i < 3; i++) {
pt[i] = createPaidTransport(i);
pt[i].queue(i);
pt[i].payFare(i);
}
}
/*
Create a subtype from the Vehicle or Plane hierarchy and
return the PublicTransport supertype
*/
static PublicTransport createPaidTransport (int i) {
PublicTransport pt;
switch (i) {
case 0:
pt = new Bus();
break;
case 1:
pt = new Taxi();
break;
default:
pt = new PassengerPlane();
}
return pt;
}
}
In the code above we are instantiating objects from totally different hierachies using the PublicTransport
interface type as the reference type. Save, compile and run the PolymorphicIntReturn
in
directory c:\_OOConcepts in the usual way.
We are returning the PublicTransport
interface type from the createPaidTransport()
method. The JVM
uses polymorphic method invocation to dynamically
invoke the correct queue()
and payFare()
methods based on the actual object type on return.
For more on polymorphism and how it works take a look at the Polymorphism lesson.
Using instanceof
With Interfaces Top
We first looked at the instanceof
operator in the Reference Variables lesson. Now we have learnt
about polymorphic types and interfaces it's time to take another look at this operator and its application. The following program uses the Vehicle
hierarchy and the PublicTransport
interface to
show some instanceof
usages:
package info.java8;
/*
A Minibus Class
*/
public class Minibus extends Bus {
public static void main(String[] args) {
Vehicle bus = new Bus();
checkType(bus);
Vehicle car = new Car();
checkType(car);
Vehicle minibus = new Minibus();
checkType(minibus);
PassengerPlane pp = new PassengerPlane();
checkType(pp);
Vehicle taxi = new Taxi();
checkType(taxi);
}
public static void checkType(Object o) {
if (o instanceof Minibus) {
((Minibus)o).MinibusClassOnlyMethod(); // Downcast to minibus
}
if (o instanceof PublicTransport ) {
/*
Downcast argument to PublicTransport interface type
*/
PublicTransportOnlyMethod(((PublicTransport)o));
}
}
private static void MinibusClassOnlyMethod() {
System.out.println("We are in the MinibusClassOnlyMethod().");
System.out.println("We have safely downcast to the Minibus class to get here.");
}
private static void PublicTransportOnlyMethod(PublicTransport pt) {
pt.queue(10);
pt.payFare(2);
}
}
In the code above we are instantiating objects from two different hierachies. We call the checkType(Object o)
which uses The Object
Superclass as a parameter. This enables us to
pass any argument to the method. Within the method we firstly use the instanceof
operator to test for a Minubus
type and if so we print some messages for that type. We then check to see if
this type is an instance of the PublicTransport
interface. If it is we cast the object argument to the PublicTransport
interface type and pass this to the PublicTransportOnlyMethod(PublicTransport pt)
method. Within this method the overridden methods for the appropriate class are called. Save, compile and run the Minibus
in directory c:\_OOConcepts in the usual way.
If you look closely at the output you will see that the queue()
and payFare()
methods are output twice for the Bus
class and yet we only made one occurrence of Bus
. The second lot of output
is actually for the Minibus
class. The reason for this is inheritance; if a superclass implements an interface, then a subclass will have an implicit implementation through the superclass.
Related Quiz
OO Concepts Quiz 11 - Deeper Into Polymorphism
Lesson 11 Complete
In this lesson we delved deeper into polymorphism by looking at polymorphic interface arguments and polymorphic interface returns.
What's Next?
In the next lesson we learn about the various ways to code nested classes within our classes.