How is the “abstract” keyword used in Java?

In Java, the abstract keyword is used to define abstract classes and methods.

An abstract class is a class that cannot be instantiated, but can only be inherited. Abstract classes are typically used to define common characteristics and behaviors, and can contain abstract methods. Abstract methods are methods without concrete implementations, only method declarations, with the specific implementation needing to be completed in the subclass. Abstract classes can also contain other non-abstract methods and properties.

Use the abstract keyword to define an abstract class.

abstract class AbstractClass {
    // 抽象方法
    public abstract void abstractMethod();

    // 非抽象方法
    public void nonAbstractMethod() {
        // 具体实现
    }
}

Abstract methods do not require concrete implementation, only the declaration of the method.

abstract void abstractMethod();

Abstract classes cannot be instantiated and can only be used through inheritance. When a subclass inherits an abstract class, it must implement all the abstract methods in the abstract class, or the subclass must also be defined as an abstract class.

Example of using abstract class and abstract methods:

abstract class Animal {
    abstract void sound();
}

class Cat extends Animal {
    void sound() {
        System.out.println("Meow");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Woof");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal cat = new Cat();
        Animal dog = new Dog();
        
        cat.sound(); // 输出 "Meow"
        dog.sound(); // 输出 "Woof"
    }
}
bannerAds