编写一个矩形,封装长和宽两个数据成员,创建这些属性的set和get方法,通过有参构造方法来完成对象的初始化,以及计算矩形的周长和面积的方法。
public class Rectangle{
//数据成员,属性
//访问修饰符(private)数据结构 变量名
private int length;
private int width;
//成员方法
public Rectangle(){
this.length=0;
this.width=0;
}
public Rectangle(int length,int width){
this.length=length;
this.width=width;
}
public void setLength(int length){
this.length=length;
}
public void setWidth(int length){
this.width=width;
}
public int getLength(){
return this.length;
}
public int getWidth(){
return this.width;
}
public int getArea(){
return length*width;
}
public int getGirth(){
return (length+width)*2;
}
}
public class RectangleTest{
public static void main(Sting[] args){
//实例化对象
//1--无参
Rectangle rec=new Rectangle();
//属性初始化赋值
rec.setLength(5);
rec.setWidth(4);
//2--有参
Rectangle rec1=new Rectangle(10,3_);
//对象调用方法
Rectangle.out.println("长"+rec.getLength()+"宽"+rec.getWidth()+"的矩形面积为"+recgetArea()+"周长为"+recGirth()}
Rectangle.out.println("长"+rec1.getLength()+"宽"+rec1.getWidth()+"的矩形面积为"+rec1getArea()+"周长为"+rec1Girth()}
}
}