定义一个矩形 Rectangle 类和 三角形 Triangle 类,都继承 Shape 类,在这两个类中分别定义 一个名为 area 的方法,实现计算该形状面积的功能(Shape 类已经定义完成,可以在 Shape.java 文件查看相应代码)。
时间: 2024-05-11 16:18:47 浏览: 178
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 area() {
return length * width;
}
}
```
Triangle 类实现:
```java
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getBase() {
return base;
}
public void setBase(double base) {
this.base = base;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
}
```
阅读全文