Can someone explain the benefits of polymorphism?

前端 未结 10 456
难免孤独
难免孤独 2021-02-01 10:41

So I understand pretty much how it works, but I just can\'t grasp what makes it useful. You still have to define all the separate functions, you still have to create an instanc

10条回答
  •  被撕碎了的回忆
    2021-02-01 11:42

    Reuse, generalisation and extensibility.

    I may have an abstract class hierarchy like this: Vehicle > Car. I can then simply derive from Car to implement concrete types SaloonCar, CoupeCar etc. I implement common code in the abstract base classes. I may have also built some other code that is coupled with Car. My SaloonCar and CoupeCar are both Cars so I can pass them to this client code without alteration.

    Now consider that I may have an interface; IInternalCombustionEngine and a class coupled with with this, say Garage (contrived I know, stay with me). I can implement this interface on classes defined in separate class hierarchies. E.G.

    public abstract class Vehicle {..}
    
    public abstract class Bus : Vehicle, IPassengerVehicle, IHydrogenPowerSource, IElectricMotor {..}
    
    public abstract class Car : Vehicle {..}
    
    public class FordCortina : Car, IInternalCombustionEngine, IPassengerVehicle {..}
    
    public class FormulaOneCar : Car, IInternalCombustionEngine {..}
    
    public abstract class PowerTool {..}
    
    public class ChainSaw : PowerTool, IInternalCombustionEngine {..}
    
    public class DomesticDrill : PowerTool, IElectricMotor {..}
    

    So, I can now state that an object instance of FordCortina is a Vehicle, it's a Car, it's an IInternalCombustionEngine (ok contrived again, but you get the point) and it's also a passenger vehicle. This is a powerful construct.

提交回复
热议问题