Wednesday, June 7, 2017

Why is Polymorphism Needed in Java?

Polymorphism(both run time and compile time) is necessary in Java for quite a few reasons.
Method overriding is a run time polymorphism and overloading is compile time polymorphism.
Few of them are(some of them are already discussed):
  1. Collections: Suppose you have multiple type of flying machines and you want to have them all in a single collection. You can just define a list of type FlyingMachines and add them all.
    List<FlyingMachine> fmList = new ArrayList<>();
    fmList.add(new new JetPlaneExtendingFlyingMachine());
    fmList.add(new PassengerPlanePlaneExtendingFlyingMachine());
    The above can be done only by polymorphism. Otherwise you would have to maintain two separate lists.
  2. Caste one type to another : Declare the objects like :
    FlyingMachine fm1 = new JetPlaneExtendingFlyingMachine();
    FlyingMachine fm2 = new PassengerPlanePlaneExtendingFlyingMachine();
    fm1 = fm2; //can be done
  3. Overloading: Not related with the code you gave, But overloading is also another type of polymorphism called compile time polymorphism.
  4. Can have a single method which accepts type FlyingMachine handle all types i.e. subclasses of FlyingMachine. Can only be achieved with Polymorphism.

No comments:

Post a Comment