What is the main advantage of making a class abstract

前端 未结 9 559
渐次进展
渐次进展 2020-12-21 06:47

Why do we declare a class as abstract? I know it cannot be instantiated, but why give a special keyword for it. Even a \'normal\' class will work just as well and can be eas

9条回答
  •  旧巷少年郎
    2020-12-21 07:16

    Just a real life example. I have a GUI abstract class that is the parent for all my GUI components. Lets call this AbstractSuperClass. Each of my components that extend AbstractSuperClass need their own implementation of the save function. So the nice thing about making my super class abstract is that I can have an array of type AbstractSuperClass that can hold all of my GUI components. I can then loop over that array and call the save function knowing that each GUI component has its own save method. Since the class is abstract, it forces my subclasses to provide a implementation of the save function.

    This is especially useful because when we open up our APIto other programmers, they dont get the source. They just extend the AbstractSuperClass and must provide a save implementation.

提交回复
热议问题