题目描述
- 定义一个长方形类MyBox,成员变量有length(长)、width(宽),方法分别有计算面积、周长、修改长、修改宽等。
- 在另一个类中使用此类的对象,验证其正确性。
核心思想
比较基础,跟着需求说明写就ok了
代码实现
- MyBox.java
package Project03;
public class MyBox {
//长
private double length;
//宽
private double width;
//无参数构造
public MyBox() {
super();
}
//全参构造
public MyBox(double length, double width) {
this.length = length;
this.width = width;
}
//设置长
public double getLength() {
return length;
}
//读取长
public void setLength(double length) {
this.length = length;
}
//设置宽
public double getWidth() {
return width;
}
//读取宽
public void setWidth(double width) {
this.width = width;
}
/**
* 计算面积(不带参数)
* @return 面积
*/
public double area() {
return this.length*this.width;
}
/**
* 计算面积(带参数)
* @param len 长
* @param width 宽
* @return 面积
*/
public double area(double len,double width) {
return len*width;
}
/**
* 求周长(无参数)
* @return 周长
*/
public double circ() {
return 2*(this.length+this.width);
}
/**
* 求周长(带参)
* @param len 长
* @param width 宽
* @return
*/
public double circ(double len,double width) {
return 2*(this.length+this.width);
}
}
- MyBoxTest.java
package Project03;
public class MyBoxTest {
public static void main(String[] args) {
//无参数的长方形
MyBox mybox = new MyBox();
//设置长
mybox.setLength(2.5);
//读取长度
System.out.println("长方形的长为:" + mybox.getLength());
//设置宽
mybox.setWidth(2.0);
//读取宽度
System.out.println("长方形的宽为:" + mybox.getWidth());
//求面积
double area = mybox.area();
System.out.println("mybox的面积:" + area);
//求周长
double circ = mybox.circ();
System.out.println("mybox的周长:" + circ);
System.out.println("=================================");
//全参的长方行
MyBox mybox1 = new MyBox(4.0,2.0);
System.out.println("长方形1的长为:" + mybox1.getLength());
System.out.println("长方形1的宽为:" + mybox1.getWidth());
System.out.println("mybox1的面积:" + mybox1.area());
System.out.println("mybox1的周长:" + mybox1.circ());
}
}
运行结果展示
本节完!
更多信息交流请加QQ:1406073270