3、实现图形类的继承: 1)形状类Shape,无属性,有一个返回0.0的求图形面积的公有方法 public double getArea(); 2)矩形类Rectangle,继承Shape类,有两个实型属性width和length, 重写从父类继承的求面积方法,求矩形的面积; 3)立方体类Box,继承自Rectangle类,有一个实型属性height, 重写从父类继承的求面积方法,求立方体表面积; 另外定义一个方法public double getVolume()求立方体的体积。使用java语言实现
时间: 2023-05-15 22:07:52 浏览: 109
以下是实现图形类的继承的Java代码:
```
public class Shape {
public double getArea() {
return 0.0;
}
}
public class Rectangle extends Shape {
private double width;
private double length;
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
@Override
public double getArea() {
return width * length;
}
}
public class Box extends Rectangle {
private double height;
public Box(double width, double length, double height) {
super(width, length);
this.height = height;
}
@Override
public double getArea() {
return 2 * (width * length + length * height + height * width);
}
public double getVolume() {
return width * length * height;
}
}
```
使用这些类,可以创建矩形和立方体对象,并调用它们的方法:
```
Rectangle rectangle = new Rectangle(2.0, 3.0);
System.out.println("Rectangle area: " + rectangle.getArea());
Box box = new Box(2.0, 3.0, 4.0);
System.out.println("Box surface area: " + box.getArea());
System.out.println("Box volume: " + box.getVolume());
```
输出:
```
Rectangle area: 6.0
Box surface area: 52.0
Box volume: 24.0
```
阅读全文