【Java】矩形类Rectangle

(1)自定义一个矩形类(Rectangle),包含的私有属性有:长(length),宽(width),包含的方法有:关于属性的setter和getter方法,即setLength,getLength,setWidth,getWidth,计算矩形面积的方法(getArea)。

(2)定义矩形类的子类正方形类(Square),包含的属性边长(side_length),和setSide(float side_length)方法(去调用矩形类setLength,setWidth,让长和宽都等于边长)。

(3)定义一个测试类(Test),测试正方形类调用getArea方法计算面积。

class Rectangle{
    private int length;
    private int width;
//    public Rectangle(int length, int width){
//        this.length = length;
//    }
    public int getLength(){
        return length;
    }
    public void setLength(int length){
        this.length = length;
    }
    public int getWidth(){
        return width;
    }
    public void setWidth(int width){
        this.width = width;
    }
    public int getArea(){
        return length * width;
    }
}
class Square extends Rectangle{
    private int side_length;
    public void setSide(int side_length){
        this.side_length = side_length;
        setLength(side_length);
        setWidth(side_length);
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();
        rectangle.setLength(7);
        rectangle.setWidth(8);
        System.out.println(rectangle.getArea());
        Square square = new Square();
        square.setSide(5);
        System.out.println(square.getArea());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值