创建一个类的两个实例,分别计算其面积和周长
时间: 2024-10-04 14:02:41 浏览: 31
创建一个类的实例并计算其面积和周长通常涉及到二维图形,比如矩形或圆形。这里我们假设有一个名为`Shape`的抽象基类,以及两个派生类`Rectangle`和`Circle`,每个都有自己的`area`和`perimeter`方法。
首先,定义`Shape`类:
```java
abstract class Shape {
abstract double area();
abstract double perimeter();
}
```
接着,定义`Rectangle`和`Circle`类:
```java
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double area() {
return length * width;
}
@Override
double perimeter() {
return 2 * (length + width);
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
@Override
double perimeter() {
return 2 * Math.PI * radius;
}
}
```
现在,我们可以创建这两个类的实例并计算它们的面积和周长:
```java
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 7);
System.out.println("Rectangle area: " + rectangle.area());
System.out.println("Rectangle perimeter: " + rectangle.perimeter());
Circle circle = new Circle(3.5);
System.out.println("Circle area: " + circle.area());
System.out.println("Circle perimeter: " + circle.perimeter());
}
}
```
阅读全文