For each geometric figure, there are some common properties, such as name, area, etc., but the methods of calculating area are different. To simplify development, write a program that defines a superclass to implement the method of entering a name, and use abstract methods to calculate the area.
Idea Analysis:
The so-called superclass is an abstract parent class. There are two methods in this abstract class, which are used to obtain the name of the figure and the area of the figure. To obtain the name of the figure, it can be achieved through the getClass().getSimpleName() method of the class; to obtain the area of the figure, because the methods of calculating the area are different, this method is an abstract method.
Define a subclass to represent a circle, the radius of the circle is obtained by constructing the method, and the area of the circle is obtained by rewriting the abstract method in the superclass, where pi can be represented by Math.PI.
Others are similar to Step 2. Parameters such as radius, length, and width are obtained through the construction method, which will save trouble.
The code is as follows:
The code copy is as follows:
public abstract class Shape {
public String getName() {//Get the name of the graph
return this.getClass().getSimpleName();
}
public abstract double getArea();//Get the area of the figure
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {//Get the radius of the circle
this.radius = radius;
}
@Override
public double getArea() {//Calculate the area of the circle
return Math.PI * Math.pow(radius, 2);
}
}
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {//Get the length and width of the rectangle
this.length = length;
this.width = width;
}
@Override
public double getArea() {//Calculate the area of the rectangle
return length * width;
}
}
public class Test {
public static void main(String[] args) {
Circle circle = new Circle(1);//Create a circular object and set the radius to 1
System.out.println("The name of the graph is: " + circle.getName());
System.out.println("The area of the figure is:" + circle.getArea());
Rectangle rectangle = new Rectangle(1, 1);//Create a rectangle object and set length and width to 1
System.out.println("The name of the graph is: " + rectangle.getName());
System.out.println("The area of the figure is: " + rectangle.getArea());
}
}
The effect is shown in the picture: