JAVA定义一个长方体类,该类拥有长、宽、高3个属性及计算体积的方法;定义一个子类继承该长方体类,增加属性重量,并增加计算长方体表面积的方法。创建长方体类及其子类的对象并测试所有方法。
时间: 2023-12-23 13:06:02 浏览: 56
好的,以下是Java定义长方体类及其子类的代码:
```java
// 长方体类
public class Cuboid {
private double length;
private double width;
private double height;
public Cuboid(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public double getVolume() {
return length * width * height;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
}
// 长方体子类
public class WeightedCuboid extends Cuboid {
private double weight;
public WeightedCuboid(double length, double width, double height, double weight) {
super(length, width, height);
this.weight = weight;
}
public double getSurfaceArea() {
return 2 * (getLength() * getWidth() + getWidth() * getHeight() + getHeight() * getLength());
}
public double getWeight() {
return weight;
}
}
```
你可以使用以下代码来测试这两个类:
```java
public class Main {
public static void main(String[] args) {
Cuboid cuboid = new Cuboid(2, 3, 4);
System.out.println("Cuboid volume: " + cuboid.getVolume());
WeightedCuboid weightedCuboid = new WeightedCuboid(2, 3, 4, 10);
System.out.println("Weighted cuboid volume: " + weightedCuboid.getVolume());
System.out.println("Weighted cuboid surface area: " + weightedCuboid.getSurfaceArea());
System.out.println("Weighted cuboid weight: " + weightedCuboid.getWeight());
}
}
```
输出结果为:
```
Cuboid volume: 24.0
Weighted cuboid volume: 24.0
Weighted cuboid surface area: 52.0
Weighted cuboid weight: 10.0
```
这验证了长方体类及其子类的方法都可以正常工作。