求矩形类面积。java方法

题意:

编写一个矩形类,包括长和宽两个属性,
和计算并返回矩形的面积和周长的方法。
然后在Test类中的程序入口创建矩形,并输出矩形的面积和周长

class Rectangle {//矩形类
    private static int length;//
    private static int weight;//宽,private封装,私有属性,则其它类不可以方法这个属性
    
    //设置属性的getter方法,外部可以通过这个获得属性的值,getXxx,Xxx为属性名
    public int getLength()
    {
        return length;
    }
    public int getWeight()
    {
        return weight;
    }
    //设置属性setXxx,外部可以对其赋值
    public void setLength(int len)
    {
        length=len;
    }
    public void setWeight(int w)
    {
        weight=w;
    }
    public int getArea()//面积方法
    {
        return length*weight;//方法可以使用成员变量
    }
    public int getPerinment()//矩形方法
    {
        return (length+weight)*2;
    }
}
public class test {
    public static void main(String[] args) {       
        Rectangle r=new Rectangle();
        r.setLength(12);
        r.setWeight(3);
        int area=r.getArea();
        int p=r.getPerinment();
        System.out.println("矩形的面积为:"+area);
        System.out.println("矩形的周长为:"+p);    
    }
}

猜你喜欢

转载自www.cnblogs.com/coke-/p/12696297.html