Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use Interface reference types in Java?

I'm about to take the final exam in my very first object-oriented programming class and I still don't understand something about the concept of polymorphism.

Let's say I have an abstract class "Vehicle" and this class has one subclass named "Aircraft". My question is, what is the different between these two codes ?

Aircraft Jetplane = new Aircraft();

and

Vehicle Jetplane = new Aircraft();
like image 713
atmosphere506 Avatar asked Jul 10 '11 18:07

atmosphere506


2 Answers

In the second, then Jetplane could be anything else that inherits from Vehicle, not just an Aircraft. For example, you could have something like

Vehicle veh = null;
if (someCondition)
    veh = new Aircraft();
else
    veh = new Boat();

That can't be done in the first sample, because a Boat is not an Aircraft.

like image 58
Puppy Avatar answered Nov 15 '22 06:11

Puppy


The first one is not polymorphic: the compile-time and run-time types of jetplane are both Aircraft.

The second one is polymorphic. The compile-time type of jetplane is Vehicle, but the runtime type is Aircraft.

like image 35
duffymo Avatar answered Nov 15 '22 07:11

duffymo