定义盒子类Box,包括三个成员变量(width,length,height),通过定义有参构造方法给三个变量赋初值,再定义一个getBox()方法用来计算盒子的体积(s),并打印输出体积的值。在测试类中中创建对象,并调用构造方法传递参数(如5,6,3)来测试?
2条回答 默认 最新
threenewbee 2023-07-02 22:31关注class Box { // 成员变量 private int width; private int length; private int height; // 有参构造方法 public Box(int width, int length, int height) { this.width = width; this.length = length; this.height = height; } // 计算盒子体积的方法 public int getBox() { int volume = width * length * height; return volume; } } public class Main { public static void main(String[] args) { // 创建盒子对象并传递参数 Box myBox = new Box(5, 6, 3); // 调用计算盒子体积的方法 int boxVolume = myBox.getBox(); // 打印输出盒子体积的值 System.out.println("盒子的体积为:" + boxVolume); } }解决 无用评论 打赏 举报