How to write an abstract class in Java?

In Java, an abstract class is a class that cannot be instantiated, and it can contain both abstract and non-abstract methods. The steps to write an abstract class in Java are as follows:

  1. Declare an abstract class using the keyword “abstract”.
  2. In an abstract class, you can include both abstract methods, which are declared using the keyword “abstract,” and non-abstract methods, which are implemented directly.
  3. If a class inherits an abstract class and does not implement the abstract methods, then that class must also be declared as an abstract class.

Here is a simple example demonstrating how to write an abstract class.

// 抽象类
abstract class Shape {
    // 抽象方法
    public abstract double getArea();

    // 非抽象方法
    public void printShape() {
        System.out.println("This is a shape.");
    }
}

// 继承抽象类
class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    // 实现抽象方法
    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5);
        System.out.println("Area of circle: " + circle.getArea());
        circle.printShape();
    }
}

In the above example, Shape is an abstract class that contains an abstract method getArea() and a non-abstract method printShape(). The Circle class inherits from the Shape class and implements the getArea() method. The Circle class is instantiated in the Main class, where its methods are called.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds