Search code examples
javapolymorphism

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();

Solution

  • 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.