【项目三】长方形类MyBox

题目描述

  1. 定义一个长方形类MyBox,成员变量有length(长)、width(宽),方法分别有计算面积、周长、修改长、修改宽等。
  2. 在另一个类中使用此类的对象,验证其正确性。

核心思想
        比较基础,跟着需求说明写就ok了


代码实现

  1. 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);
	}
}
  1. 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
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值