定义抽象类 Shape,其中包含抽象方法 double getPeremeterO求周长和 doublegetArea0求面积。 定义一个矩形类,继承此抽象类,并自行扩充成员变量和方法,定义一个方法 一次直接显示长和宽、周长和面积。 定义一个测试类,测试矩形类。
时间: 2024-01-21 18:18:26 浏览: 96
下面是代码实现:
```java
// Shape.java
public abstract class Shape {
public abstract double getPerimeter();
public abstract double getArea();
}
// Rectangle.java
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
@Override
public double getArea() {
return length * width;
}
public void display() {
System.out.println("Length: " + length + ", Width: " + width + ", Perimeter: " + getPerimeter() + ", Area: " + getArea());
}
}
// Test.java
public class Test {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
rectangle.display();
}
}
```
输出结果为:
```
Length: 5.0, Width: 10.0, Perimeter: 30.0, Area: 50.0
```
阅读全文