Java example code for calculating geometric area

  • 2020-04-01 03:02:09
  • OfStack

For each geometry, there are some common attributes, such as name, area, etc., but the method of calculating the area is different. To simplify development, write a program that defines a superclass to implement a method to enter a name, and USES an abstract method to calculate the area.

Thought analysis:

The so-called superclass is the abstract parent class, which has two methods to get the name of the graph and the area of the graph. To get the name of the graph, use the getClass().getsimplename () method of the class. To obtain the area of a graph, this method is an abstract method because the area is calculated in different ways.
Define a subclass to represent a circle, the radius of which is obtained by the constructor, and the area of which is obtained by overriding the abstract method in the superclass, where PI can be represented by math.pi.
As in step 2, parameters such as radius, length and width are obtained by constructing method, which is convenient.
      The code is as follows:


public abstract class Shape {
    public String getName() {//Gets the name of the graph
        return this.getClass().getSimpleName();
    }
    public abstract double getArea();//Get the area of the graph
}
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 the circle 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);//Creates a rectangle object and sets its 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 as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201403/201431162341001.png" >


Related articles: