加深对构造方法的理解:定义一个长方形类,属性包括高和宽,计算周长、面积

1、题目

定义长方形类,含:属性:宽、高(整型);

构造方法3个:(1)无参——宽、高默认值为1;(2)1个参数——宽、高相等;(3)2个参数——宽、高各为参数值。

方法:求周长、面积;

要求:进行测试计算周长和面积。

2、代码

package com.situ.day6;


//2、定义长方形类,含:
//        属性:宽、高(整型);
//        构造方法3个:(1)无参——宽、高默认值为1;(2)1个参数——宽、高相等;(3)2个参数——宽、高各为参数值。
//        方法:求周长、面积;
//        要求:进行测试计算周长和面积。
public class Rectangle {
    private int width;
    private int height;

    public Rectangle() { //无参构造方法设置默认值
        this.width = 1;
        this.height = 1;
    }

    public Rectangle (int width) { //一个参数
        this.width = width;
        height = width; //宽高相等
    }

    public  Rectangle (int width, int height) { //两个参数
        this.width = width;
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    //方法
    //求周长
    public int getPerimeter(int width, int height) {
        return width * 2 + height * 2;
    }

    //求面积
    public int getArea(int width, int height) {
        return width * height;
    }

    public static void main(String[] args) {
        int width = 0;
        int height = 0;
        //调用无参构造方法构造长方形对象
        Rectangle rectangle1 = new Rectangle();
        width = rectangle1.getWidth();
        height = rectangle1.getHeight();
        System.out.println("调用无参构造方法时:");
        System.out.println("周长为:" + rectangle1.getPerimeter(width, height));
        System.out.println("面积为:" + rectangle1.getArea(width, height));

        //调用一个参数的构造方法时
        Rectangle rectangle2 = new Rectangle(2);
        width = rectangle2.getWidth();
        height = rectangle2.getHeight();
        System.out.println("调用一个参数的构造方法时:");
        System.out.println("周长为:" + rectangle2.getPerimeter(width, height));
        System.out.println("面积为:" + rectangle2.getArea(width, height));

        //调用两个参数的构造方法时
        Rectangle rectangle3 = new Rectangle(2, 3);
        width = rectangle3.getWidth();
        height = rectangle3.getHeight();
        System.out.println("调用两个参数的构造方法时:");
        System.out.println("周长为:" + rectangle3.getPerimeter(width, height));
        System.out.println("面积为:" + rectangle3.getArea(width, height));

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值