用上转型对象实现计算矩形和圆形的周长和面积的程序
时间: 2024-05-10 14:19:46 浏览: 48
Java实现运用上转型对象抽象方法计算圆形或圆锥的面积、周长等成员变量
好的,这是一个关于编程的问题,我会尽力回答。使用Java语言,可以定义一个抽象的Shape类,矩形类和圆形类都继承Shape类,并实现计算周长和面积的方法。定义一个计算类,传入Shape类的实例,根据实例的类型调用相应的方法,计算出周长和面积。关于具体的代码实现,请参考下面的示例:
```
abstract class Shape {
public abstract double getPerimeter();
public abstract double getArea();
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public double getArea() {
return width * height;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
class Calculator {
public void calculate(Shape shape) {
double perimeter = shape.getPerimeter();
double area = shape.getArea();
System.out.println("Perimeter: " + perimeter);
System.out.println("Area: " + area);
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
Shape rect = new Rectangle(2, 4);
Shape circle = new Circle(5);
calculator.calculate(rect);
calculator.calculate(circle);
}
}
```
希望对您有帮助。
阅读全文