java类实验长方形圆的计算
时间: 2024-10-16 12:05:38 浏览: 28
在Java中,你可以创建一个名为"Shape"的抽象类或接口,作为所有形状的基础,然后分别创建"Rectangle"(矩形)和"Circle"(圆形)两个类,它们都继承自"Shape"并实现必要的计算方法。
例如:
```java
// Shape接口或抽象类
interface Shape {
double calculateArea();
double calculatePerimeter();
}
// Rectangle类
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
}
// Circle类
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
// 使用场景
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 4);
Shape circle = new Circle(3);
System.out.println("Rectangle area: " + rectangle.calculateArea());
System.out.println("Rectangle perimeter: " + rectangle.calculatePerimeter());
System.out.println("Circle area: " + circle.calculateArea());
System.out.println("Circle perimeter: " + circle.calculatePerimeter());
}
}
```
在这个例子中,虽然Rectangle和Circle是不同的形状,但是通过Shape接口它们都能提供统一的calculateArea()和calculatePerimeter()方法来进行面积和周长的计算,这就是多态的应用。
阅读全文