-
Polymorphism is an important topic of object-oriented programming.
It is also very powerfull.
-
Let's say you had a class called Controller that uses the classes discussed
in the previous slide. It instantiates an objects of class Cavalier
and Hybrid. Then, it passes them to another method as type Vehicle.
The other method executes the go() method on both objects. Which
go method gets executed?
// Class controller uses the Vehicle classes.
public class Controller {
// Default constructor.
public Controller() {
}
// Begin method instantiates two vehicles and
passes them to run.
public void begin() {
Cavalier car1 = new
Cavalier(6, 2, 4);
Hybrid car2 = new Hybrid(5,
8, 4, 5, 68);
run(car1);
run(car2);
}
// run executes the go() method on the vehicle
passed in.
public void run(Vehicle v) {
v.go(10);
}
// Instantiate and start a Controller object.
public static void main(String[] args) {
Controller controller
= new Controller();
controller.begin();
}
}
-
The answer may suprize you.
-
For the Cavalier object, car1, there is only one go() method to run - the
method defined in class Vehicle. Therefore, that is the method run.
-
However, the Hybrid object, car2, overrides the go() method. But
wait, the run() method of class Controller accepts a Vehicle type, not
a Hybrid type, so wouldn't it run the method in Vehicle? No, it would
not. Polymorphism states that the go() method in Hybrid should
be run. Java knows how to do this via dynamic binding.
-
What if we wanted to run one of the methods specific to class Hybrid in
this method? We can't, unless we cast it to a Hybrid.
-
And while we're at it...
-
Yes, we did pass an object of type Car and an object of type Hybrid into
a method that accepts a parameter of type Vehicle. This is perfectly
legal. We can pass an object as a parameter if:
-
That object type is the same as the object type in the parameter
list of the method, or
-
That object type is a subclass of the object type in the parameter
list of the method.
Pretty crazy, huh?
More about Polymorphism and Dynamic Binding


