How to create an abstract class in Java?

To create an abstract class, you need to use the keyword ‘abstract’. An abstract class is a type of class that cannot be instantiated, it can only be inherited. Here is an example code for creating an abstract class:

public abstract class AbstractClass {
    // 抽象方法
    public abstract void abstractMethod();
    
    // 普通方法
    public void normalMethod() {
        System.out.println("这是一个普通方法");
    }
}

In the example above, AbstractClass is an abstract class that contains an abstract method, abstractMethod(), and a normal method, normalMethod(). The abstract method does not have a method body, only a method declaration, while the normal method has a method body.

Noticing the keyword ‘abstract’ before a class name signifies that it is an abstract class. Abstract classes can contain both abstract methods that must be implemented in subclasses, as well as non-abstract methods that can either have default implementations in the abstract class or be overridden in subclasses.

If a class inherits an abstract class, it must implement all abstract methods in the abstract class unless it is also declared as an abstract class.

Here is an example of inheriting an abstract class:

public class ConcreteClass extends AbstractClass {
    // 实现抽象方法
    public void abstractMethod() {
        System.out.println("这是一个抽象方法的实现");
    }
}

ConcreteClass is a concrete class that inherits from AbstractClass and implements the abstract method abstractMethod().

It is important to note that abstract classes cannot be directly instantiated, they can only be used as parent classes for other classes. Abstract class methods can be used by creating an instance of a concrete class that inherits from the abstract class.

bannerAds