使用抽象类计算图形的周长和面积
时间: 2023-07-30 18:07:00 浏览: 120
好的,您可以按照以下步骤使用抽象类计算图形的周长和面积:
1. 定义一个抽象类`Shape`,它包含两个抽象方法`getArea()`和`getPerimeter()`,分别用于计算图形的面积和周长;
2. 在`Shape`类中定义一个`name`属性,用于表示图形的名称;
3. 定义三个具体的类`Square`、`Rectangle`和`Circle`,它们继承于`Shape`类,并实现`getArea()`和`getPerimeter()`方法,分别用于计算正方形、长方形和圆形的面积和周长;
4. 在`Square`、`Rectangle`和`Circle`类中重写`Shape`类中的`name`属性,分别赋值为"正方形"、"长方形"和"圆形"。
以下是代码示例:
```java
abstract class Shape {
protected String name;
public Shape(String name) {
this.name = name;
}
public abstract double getArea();
public abstract double getPerimeter();
}
class Square extends Shape {
private double side;
public Square(double side) {
super("正方形");
this.side = side;
}
public double getArea() {
return side * side;
}
public double getPerimeter() {
return 4 * side;
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
super("长方形");
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
super("圆形");
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape square = new Square(5);
System.out.println(square.name + "的面积为:" + square.getArea());
System.out.println(square.name + "的周长为:" + square.getPerimeter());
Shape rectangle = new Rectangle(3, 4);
System.out.println(rectangle.name + "的面积为:" + rectangle.getArea());
System.out.println(rectangle.name + "的周长为:" + rectangle.getPerimeter());
Shape circle = new Circle(2);
System.out.println(circle.name + "的面积为:" + circle.getArea());
System.out.println(circle.name + "的周长为:" + circle.getPerimeter());
}
}
```
在这个程序中,`Shape`类是抽象类,它包含了`name`属性和两个抽象方法`getArea()`和`getPerimeter()`。`Square`、`Rectangle`和`Circle`类继承于`Shape`类,并实现了`getArea()`和`getPerimeter()`方法。在`Square`、`Rectangle`和`Circle`类中重写了`Shape`类中的`name`属性。在`Main`类中,通过实例化`Square`、`Rectangle`和`Circle`类,分别计算了它们的面积和周长,并输出结果。
阅读全文