定义一个矩形类Rectangle

#定义一个矩形类Rectangle:
1 定义三个方法:getArea()求面积、getPer()求周长,showAll()分别在控制台输出长、宽、面积、周长。
2 有2个属性:长length、宽width
3 通过构造方法Rectangle(int width, int length),分别给两个属性赋值
4 创建一个Rectangle对象,并输出相关信息

class Rectangle{
	private int length;
	private int width;
	//构造方法
	Rectangle(int length,int width){
		this.length=length;
		this.width=width;
	}
	//控制台显示长,宽,面积,周长
	public void showAll(){
		System.out.println("矩形长为:"+length+"\t"+"矩形的宽为:"+width+"\t"+"矩形的面积为:"+getArea()+"\t"+"矩形的周长为:"+getPer());
	}
	//求周长
	public int getPer(){
		return 2*(length+width);
	}
	//求面积
	public int getArea(){
		return length*width;
	}
	//
}
class RectangleDemo{
	public static void main(String[] args){
		Rectangle r=new Rectangle(2,3);
		r.showAll();
	}
}
发布了164 篇原创文章 · 获赞 440 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_45884316/article/details/104960591