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):
- 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. - Caste one type to another : Declare the objects like :
FlyingMachine fm1 = new JetPlaneExtendingFlyingMachine(); FlyingMachine fm2 = new PassengerPlanePlaneExtendingFlyingMachine(); fm1 = fm2; //can be done
- Overloading: Not related with the code you gave, But overloading is also another type of polymorphism called compile time polymorphism.
- Can have a single method which accepts type
FlyingMachine
handle all types i.e. subclasses of FlyingMachine. Can only be achieved withPolymorphism
.
No comments:
Post a Comment