定义一个图形类及其子类(三角形类和矩形类),分别计算其面积和周长。

题目:

       定义一个图形类及其子类(三角形类和矩形类),分别计算其面积和周长。


代码:



//矩形类
class Rectangle {
	private int width;
	private int length;
	public Rectangle(int width,int length) {
		super();
		this.width = width;
		this.length = length;
	}
	public int getPerimeter(){
		return this.width *2 + this.length *2;
	}
	//获得周长
	public int getArea(){
		return this.width * this.length;
	}
	//面积
}
//三角形类
class Triangle {
	private int height;
	private int end;
	private int left;
	private int right;
	public Triangle(int height, int end,int left,int right) {
		super();
		this.height = height;
		this.end = end;
		this.left = left;
		this.right = right;
	}
	public int getPerimeter(){
		return this.end+this.left+this.right;
	}
	//获得周长
	public int getArea(){
		return (this.end * this.height)/2;
	}
	//面积

}


public class Figure {
	public static void main(String[] args) {
		Rectangle rec = new Rectangle(12,14);
		Triangle tri = new Triangle(8, 10, 9, 11);
		System.out.println("矩形的面积是:"+rec.getArea());
		System.out.println("矩形的周长是:"+rec.getPerimeter());
		System.out.println("三角形的面积是:"+tri.getArea());
		System.out.println("三角形的周长是:"+tri.getPerimeter());
	}


}



软件运行结果:

定义一个图形类及其子类(三角形类和矩形类),分别计算其面积和周长。_第1张图片


你可能感兴趣的:(作业)