Why not override instead of using abstract class?

前端 未结 6 1916
北恋
北恋 2021-01-13 19:11

This might be a simple question for many but has confused me. I am picking an example from Kathy Sierra that shows the utility of Abstract Classes but I am unable to underst

6条回答
  •  迷失自我
    2021-01-13 19:37

    Why not have these two methods in any one of these car subtypes, say BMW and then other two - Volkswagen and Audi - can simply override these methods?

    Wouldn't that require Volkswagen and Audi to inherit from BMW? That wouldn't be correct, since those aren't BMWs.

    The abstract base class and its abstract methods form a kind of contract which inheriting objects must implement. There's no such thing as a concrete Car that isn't a more specific type. But all concrete types share commonalities. The abstract Car enforces those commonalities, allowing specific types to be treated as generic instances of Car when needed.

    For example, if you have code which needs a Car on which it will invoke the Drive() method, that code doesn't care what kind of Car it gets. It will Drive() any Car. So it accepts an abstract type so that anything which implements that type can be used:

    UseACar(Car car)
    {
        car.Drive();
    }
    
    // elsewhere
    
    BMW myCar = new BMW();
    UseACar(myCar);
    

    Without this enforcement of the contract, a statically-typed and compiled language would have no way of guaranteeing that .Drive() exists on the object. You'd need to create a UseAX() method for every possible kind of car, each accepting a different type. Using polymorphism like this allows you to create a single, more generic method which works on any instance of the abstract type.

提交回复
热议问题