1. 程式人生 > >課後第三題

課後第三題

3.1 設計Shape表示圖形類,有面積屬性area、周長屬性per,顏色屬性color,有兩個構造方法(一個是預設的、一個是為顏色賦值的),還有3個抽象方法,分別是:getArea計算面積、getPer計算周長、showAll輸出所有資訊,還有一個求顏色的方法getColor。
`private double area;
private double pre;
private String color;

public Shape(String color) {
	super();
	this.color = color;
}

public String getColor() {
	return color;
}

public Shape() {

}

abstract void getArea();

abstract void showAll();

abstract void per();`
3.2 設計 2個子類:

3.2.1 Rectangle表示矩形類,增加兩個屬性,Width表示長度、height表示寬度,重寫getPer、getArea和showAll三個方法,另外又增加一個構造方法(一個是預設的、一個是為高度、寬度、顏色賦值的)。

private double width;
			private double height;
			@Override
			void getArea() {
	
			System.out.println("面積為"+this.height*this.width+"顏色為"+super.getColor());	
			}
			@Override
			void showAll() {
			System.out.println("這個矩形的長為"+this.width+"這個矩形的寬"+this.height+"面積為"+this.height*this.width+"周長為"+(this.height+this.width)*2+"顏色為"+super.getColor());	
				
			}
			@Override
			void per() {
			System.out.println("這個矩形的周長為"+(this.height+this.width)*2+"顏色為"+super.getColor());
				
			}
			public Rectangle(double width, double height) {
			
				this.width = width;
				this.height = height;
			}
			public Rectangle(String color, double width, double height) {
				super(color);
				this.width = width;
				this.height = height;
			}
			public Rectangle(String color) {
				super(color);
			}
			

3.2.2 Circle表示圓類,增加1個屬性,radius表示半徑,重寫getPer、getArea和showAll三個方法,另外又增加兩個構造方法(為半徑、顏色賦值的)。

private double radius;
	
	@Override
	void getArea() {
		System.out.println(3.14*radius*radius);
	}

	@Override
	void showAll() {
	System.out.println("該圓半徑為"+radius);
	getArea();
	 per() ;
	}

	@Override
	void per() {
		System.out.println("該圓周長為"+6.28*radius);
		
	}

	public Circle(String color, double radius) {
		super(color);
		this.radius = radius;
	}

	public Circle(String color) {
		super(color);
	}
			

3.3 測試類中,在main方法中,宣告建立每個子類的物件,並呼叫2個子類的showAll方法。

Shape s = new Rectangle("yellow", 10, 20);
		s.showAll();
		s.getArea();
		s.per();
		System.out.println();
		Shape s1 = new Circle("ysllow", 10);
		s1.per();
		s1.getArea();
		s1.showAll();

	}