1.设计一个盒类Box,它有长、宽、高三
个私有成员属性,包含无参数和有参数的构
造方法,以及求盒子体积的公有方法,以及
打印属性的方法 print 。其中,构造方法用于
对成员变量初始化,无参数的构造方法将成
员变量初始化为0,有参的构造方法初始化所
有的属性。写两个及以上的 print 方法,实现
方法的重载。再编写一个主类 BoxTest ,在
其主方法 main 中创建若干个 Box 对象,调
用方法,测试编写的方法是否正确。
引用 皆我百晓生 小程序回复内容作答:
以下是Java语言中的实现:
public class Box {
private double length;
private double width;
private double height;
public Box() {
this.length = 0;
this.width = 0;
this.height = 0;
}
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public void print() {
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Height: " + height);
}
public void print(String prefix) {
System.out.println(prefix + " Length: " + length);
System.out.println(prefix + " Width: " + width);
System.out.println(prefix + " Height: " + height);
}
public double calculateVolume() {
return length * width * height;
}
}
public class BoxTest {
public static void main(String[] args) {
Box box1 = new Box();
Box box2 = new Box(2.0, 3.0, 4.0);
Box box3 = new Box(5.0, 6.0, 7.0);
box1.print();
box2.print("Box 2:");
box3.print("Box 3:");
System.out.println("Box 2 volume: " + box2.calculateVolume());
System.out.println("Box 3 volume: " + box3.calculateVolume());
}
}
在主类 BoxTest 的主方法中,首先创建了三个 Box 对象 box1、box2 和 box3,并使用不同的构造方法进行初始化。然后分别调用了 Box 对象的 print 方法,测试方法的重载。最后计算并打印了 box2 和 box3 的体积。