For each geometry, there are some common attributes, such as name, area, and so on, and the method of calculating the area is different. To simplify development, write a program that defines a superclass to implement the method of entering a name and uses an abstract method to compute the area.
Thinking Analysis:
The superclass is the abstract parent class, which has two methods to get the name of the graphic and the area of the graphic. To get the name of the graphic, the method is an abstract method by using the GetClass (). Getsimplename () method of the class, to get the area of the graphic, because the method of calculating the area varies.
Defines a subclass that represents a circle, the radius of the circle is obtained by the construction method, and the area of the circle is obtained by overriding the abstract method in the superclass, in which PI can be represented by Math.PI.
Other similar steps 2, radius, length, width and other parameters obtained by the construction method, so it is convenient.
The code is as follows:
Copy Code code as follows:
Public abstract class Shape {
Public String GetName () {//Get the name of the graphic
Return This.getclass (). Getsimplename ();
}
public abstract Double Getarea ()//Get the area of the graphic
}
public class Circle extends Shape {
private double radius;
Public Circle (double radius) {//Get the radius of a circle
This.radius = radius;
}
@Override
Public double Getarea () {//Calculate the area of a 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 a rectangle
return length * width;
}
}
public class Test {
public static void Main (string[] args) {
Circle Circle = new Circle (1);//Create Circle object and set radius to 1
System.out.println ("Graphic name is:" + circle.getname ());
System.out.println ("The area of the graph is:" + Circle.getarea ());
Rectangle Rectangle = new Rectangle (1, 1);//Create a rectangular object and set the length and width to 1
System.out.println ("Graphic name is:" + rectangle.getname ());
System.out.println ("The area of the graph is:" + Rectangle.getarea ());
}
}
Effect as shown: