# 长方体Box类实现 以下是完整的Box类实现及测试代码: ```java public class Box { private int length; private int width; private int height; // 构造方法初始化长宽高 public Box(int length, int width, int height) { this.length = length; this.width = width; this.height = height; } // 计算体积 public int calculateVolume() { return length * width * height; } // 计算表面积 public int calculateSurfaceArea() { return 2 * (length * width + length * height + width * height); } // 转化为字符串 @Override public String toString() { return "Box[length=" + length + ", width=" + width + ", height=" + height + ", volume=" + calculateVolume() + ", surfaceArea=" + calculateSurfaceArea() + "]"; } } // 测试类 public class TestBox { public static void main(String[] args) { Box box = new Box(10, 20, 30); System.out.println("体积: " + box.calculateVolume()); System.out.println("表面积: " + box.calculateSurfaceArea()); System.out.println(box.toString()); } } ``` 代码说明: 1. Box类包含三个私有成员变量length、width和height 2. 构造方法用于初始化这三个变量 3. calculateVolume()方法计算并返回体积 4. calculateSurfaceArea()方法计算并返回表面积 5. toString()方法返回包含所有信息的字符串 6. TestBox类创建Box实例并测试所有方法 测试代码输出示例: ``` 体积: 6000 表面积: 2200 Box[length=10, width=20, height=30, volume=6000, surfaceArea=2200] ``` 三条额外需要注意的逻辑点: 1. 体积计算是长×宽×高,而表面积计算是2×(长×宽+长×高+宽×高) 2. toString()方法中调用了calculateVolume()和calculateSurfaceArea()方法,确保每次调用都能获取最新计算结果 3. 成员变量设为private符合封装原则,防止外部直接修改 [2025-05-19 11:49:11 | AI写代码神器 | 480点数解答]