1, 帮我用Java编完整代码: 使用抽象类的知识设计一个程序,计算不同图形的面积和周长。
时间: 2024-05-08 20:18:27 浏览: 109
好的,很高兴回答您的问题。以下是使用Java抽象类设计计算不同图形面积和周长的完整代码:
```
abstract class Shape {
protected String name;
Shape(String name) {
this.name = name;
}
public abstract double getArea();
public abstract double getPerimeter();
}
class Circle extends Shape {
protected double radius;
Circle(String name, double radius) {
super(name);
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
protected double width;
protected double height;
Rectangle(String name, double width, double height) {
super(name);
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getPerimeter() {
return 2 * (width + height);
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle("Circle", 5);
System.out.println(circle.name + " area is " + circle.getArea());
System.out.println(circle.name + " perimeter is " + circle.getPerimeter());
Rectangle rectangle = new Rectangle("Rectangle", 3, 4);
System.out.println(rectangle.name + " area is " + rectangle.getArea());
System.out.println(rectangle.name + " perimeter is " + rectangle.getPerimeter());
}
}
```
在此代码中,我们定义了一个抽象类Shape来表示不同的形状,并定义了两个子类:圆形和矩形。每个子类都覆盖了Shape类中的getArea()和getPerimeter()方法。在程序的main()函数中,我们实例化了圆形和矩形对象,并调用它们的getArea()和getPerimeter()方法来计算它们的面积和周长。
希望这个回答对您有所帮助。
阅读全文