用Java设计盒子类CBox
时间: 2024-11-15 10:24:00 浏览: 10
在Java中,设计一个名为`CBox`的盒子类(通常称为`Box`或者`Carton`),可以包含一些基本属性如长度、宽度和高度,以及相应的封装方法来操作这些属性。下面是一个简单的`CBox`类的设计示例:
```java
public class CBox {
// 定义私有变量来存储盒子里的尺寸
private double length;
private double width;
private double height;
// 构造函数用于初始化盒子的尺寸
public CBox(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
// 获取盒尺寸的方法
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
// 设置盒尺寸的方法(setters)
public void setLength(double length) {
if (length > 0) {
this.length = length;
} else {
throw new IllegalArgumentException("Length must be positive.");
}
}
public void setWidth(double width) {
if (width > 0) {
this.width = width;
} else {
throw new IllegalArgumentException("Width must be positive.");
}
}
public void setHeight(double height) {
if (height > 0) {
this.height = height;
} else {
throw new IllegalArgumentException("Height must be positive.");
}
}
// 计算体积的方法(getVolume)
public double getVolume() {
return length * width * height;
}
// 返回一个描述这个盒子的字符串
@Override
public String toString() {
return "CBox[length=" + length + ", width=" + width + ", height=" + height + "]";
}
}
```
阅读全文