What is the main advantage of making a class abstract

前端 未结 9 551
渐次进展
渐次进展 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:28

    I think you misunderstand the point of abstract classes: they provide a partial implementation of some functionality, but not a complete implementation.

    You suggested that abstract classes were redundant because you can define incomplete methods using public void methodname(){} -- which is certainly ok. However, let's say your clients inherit from a class defined in such a way, how do they know which methods to override? What happens if they forget to override a method? Now their derived class has an incomplete definition -- you don't want that.

    The abstract keyword forces clients to provide implementations for certain methods, otherwise the code won't even compile. In other words, it provides a compile-time guarantee that classes you use or create are fully implemented.

提交回复
热议问题