Abstract class in Java

后端 未结 14 1558
孤独总比滥情好
孤独总比滥情好 2020-11-22 12:32

What is an \"abstract class\" in Java?

14条回答
  •  醉话见心
    2020-11-22 13:03

    A Java class becomes abstract under the following conditions:

    1. At least one of the methods is marked as abstract:

    public abstract void myMethod()
    

    In that case the compiler forces you to mark the whole class as abstract.

    2. The class is marked as abstract:

    abstract class MyClass
    

    As already said: If you have an abstract method the compiler forces you to mark the whole class as abstract. But even if you don't have any abstract method you can still mark the class as abstract.

    Common use:

    A common use of abstract classes is to provide an outline of a class similar like an interface does. But unlike an interface it can already provide functionality, i.e. some parts of the class are implemented and some parts are just outlined with a method declaration. ("abstract")

    An abstract class cannot be instantiated, but you can create a concrete class based on an abstract class, which then can be instantiated. To do so you have to inherit from the abstract class and override the abstract methods, i.e. implement them.

提交回复
热议问题