Why not override instead of using abstract class?

前端 未结 6 1930
北恋
北恋 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:48

    So that you can write code that deals with Cars without knowing what kind of car it is:

    public void PrintTopSpeed(Car car)
    {
        System.out.println("This car's top speed is " + car.topSpeed());
    }
    

    If the Car class didn't define topSpeed(), this code wouldn't compile. You'd have to have a different version of this print function for each of your BMW, Volkswagen, Audi, etc. derived classes. This is perhaps the most basic concept in object-oriented programming, so you really need to master it. Base classes allow objects to share common behavior, and allow code to be written to use that behavior without any knowledge of what specific type of object it's dealing with.

提交回复
热议问题