Java + 面向抽象abstract類與函數實現(計算三角形、圓形的面積)

本次進行面向抽象abstract類與函數實現,其內功能爲計算三角形和圓形的面積。


所謂面向抽象編程是指當設計某種重要的類時,不讓該類面向具體的類,而是面向抽象類,及所設計類中的重要數據是抽象類聲明的對象,而不是具體類聲明的對象。就 利用abstract來設計實現用戶需求。


第一步:定義一個抽象類Geometry,類中定義一個抽象的getArea()方法,Geometry類如下。這個抽象類將所有計算面積的方法都抽象爲一個標識:getArea()無需考 慮算法細節。

public abstract class Geometry{
    public abstract double getArea();
}

一個非抽象類是某個抽象類(如Geometry)的子類,那麼它必須重寫父類的抽象方法(如getArea()),給出方法體。


================================================================================================================================

在以下完整測試中

我們會使用到五個類   1.Pillar   2.Geometry   3.Lader   4.Circle   5.Example5_10

.

.

1.Pillar

.

.

.


2. Geometry(抽象類)


.

.

.

3.Lader

.

.

.

4.Circle

.

.

.

5.Example5_10測試類

.

.


================================================================================================================================

.

我們來看一看代碼實現

.

.


//柱體Pillar類

package com.ash.www;

public class Pillar{

	Geometry bottom;	//將Geometry對象做完成員
	double height;		//高
	
	Pillar(Geometry bottom, double height){	//定義構造函數
		this.bottom = bottom;
		this.height = height;
	}
	void changeBottom(Geometry bottom){
		this.bottom = bottom;
	}
	public double getVolume(){
		return bottom.getArea() * height;
	}
}

.

.

.

//幾何Geometry類(抽象類)

package com.ash.www;

public abstract class Geometry {
	
	public abstract double getArea();

}
.

.

.

//梯形Lader類

package com.ash.www;

public class Lader extends Geometry{	//繼承抽象類Geometry
	double a, b, h;
	
	Lader(double a, double b, double h){
		this.a = a;
		this.b = b;
		this.h = h;
	}
	public double getArea(){
		return (1 / 2.0) * (a + b) * h;
	}

}

.

.

.

//圓形Circle類

package com.ash.www;

public class Circle extends Geometry{	//繼承抽象類Geometry
	double r;
	
	Circle(double r){
		this.r = r;
	}
	public double getArea(){
		return (3.14 * r * r);
	}
	
}
.

.

.

//Example5_10測試類

package com.ash.www;

public class Example5_10 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Pillar pillar;
		Geometry tuxing;
		
		tuxing = new Lader(12, 22, 100);	//tuxing作爲Lader對象的引用
		System.out.println("Lader area :"+ tuxing.getArea());
		
		pillar = new Pillar(tuxing, 58);	
		System.out.println("Ladered pillar area :"+ pillar.getVolume());
		
		tuxing = new Circle(10);	//tuxing作爲Circle對象的引用
		System.out.println("When radius = 10, the circle area :"+ tuxing.getArea());
		
		pillar.changeBottom(tuxing);	
		System.out.println("Circled pillar area :"+ pillar.getVolume());
		
	}

}
.

.

.

.

看完這篇文章,你是否對面向抽象abstract類與函數實現又有了更深的瞭解呢?





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