java練習 繼承04

 題目:

(1)編寫一個圓類Circle,該類擁有:
①一個成員變量
radius(私有,雙精度型);  // 存放圓的半徑;
②兩個構造方法
Circle( )                 // 將半徑設爲0
Circle(double  r )         //創建Circle對象時將半徑初始化爲r
③ 三個成員方法
double getArea( )       //獲取圓的面積
double getPerimeter( )   //獲取圓的周長
void  show( )          //將圓的半徑、周長、面積輸出到屏幕
(2)編寫一個圓柱體類Cylinder,它繼承於上面的Circle類。還擁有:
①一個成員變量
double hight(私有,雙精度型);  // 圓柱體的高;
②構造方法
Cylinder (double r, double  h )           //創建Circle對象時將半徑初始化爲r
③ 成員方法
double getVolume( )             //獲取圓柱體的體積
void  showVolume( )             //將圓柱體的體積輸出到屏幕
編寫應用程序,創建類的對象,分別設置圓的半徑、圓柱體的高,計算並顯示圓半徑、圓面積、圓周長,圓柱體的體積。

代碼: 

public class Circle {
//	①一個成員變量
//	radius(私有,雙精度型);  // 存放圓的半徑;
	private double radius;
//	②兩個構造方法
//	Circle( )                 // 將半徑設爲0
//	Circle(double  r )         //創建Circle對象時將半徑初始化爲r

	public Circle(double r) {
		this.radius = r;
	}

	public Circle() {
		this.radius = 0;
	}
//	③ 三個成員方法
//	double getArea( )       //獲取圓的面積
//	double getPerimeter( )   //獲取圓的周長
//	void  show( )          //將圓的半徑、周長、面積輸出到屏幕
	public double getArea(){
		return Math.PI *this.radius*this.radius;
	}
	public double getPerimeter(){
		return this.radius*Math.PI*2;
	}

	public void show() {
		System.out.println( "Circle [半徑=" + radius + ", 面積=" + getArea() + ", 周長=" + getPerimeter() + "]");
	}
	

}
public class Cylinder extends Circle{
//	①一個成員變量
//	double hight(私有,雙精度型);  // 圓柱體的高;
	private double hight;
//	②構造方法
//	Cylinder (double r, double  h )  
//創建Circle對象時將半徑初始化爲r

public Cylinder(double r, double h) {
	super(r);
	this.hight = h;
}

	
//	③ 成員方法
//	double getVolume( )             //獲取圓柱體的體積
//	void  showVolume( )             //將圓柱體的體積輸出到屏幕
	public double getVolume(){
		return super.getArea()*this.hight;
	}
	public void  showVolume(){
		System.out.println("體積:"+getVolume());
	}
}
public class Test {
/*
 * 編寫應用程序,創建類的對象,分別設置圓的半徑、圓柱體的高,
 * 計算並顯示圓半徑、圓面積、圓周長,圓柱體的體積。
 */
	public static void main(String[] args) {
		Cylinder c = new Cylinder(2, 3);
		c.show();
		c.showVolume();

	}

}

輸出結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章