關於面對抽象程式設計的一些初步理解
阿新 • • 發佈:2019-02-09
對程式的解讀:
首先定義一個抽象類Geometry,底面不確定為什麼形狀,定義抽象方法用於求底面的面積,抽象方法,只能宣告,不能實現
public abstract double getArea();
然後定義一個非抽象的類Pillar,採用構造方法,傳入兩個引數,第一個為抽象類求得的面積方法,(需要定義抽象類的子類,重寫抽象方法),另一個是柱體的高
接下來定義求柱體體積的方法
定義抽象類的兩個子類,分別為Circle和Rectangle
重寫抽象方法
定義Application類,進行測試
main類中,為Geometry建立物件bottom,建立它的上轉型物件
bottom = new Circle(3);
建立物件Pillar pillar = new Pillar(bottom,6)
三角形底流程類似,自行理解
public abstract class Geometry { public abstract double getArea(); } public class Pillar { Geometry bottom; double height; //構造方法 Pillar(Geometry bottom,double height) { this.bottom = bottom; this.height = height; } //求體積 public double getVolume() { return bottom.getArea()*height; } } public class Circle extends Geometry { double r; Circle (double r) { this.r = r; } public double getArea() { return 3.14*r*r; } } public class Rectangle extends Geometry { double a,b; Rectangle(double a,double b) { this.a = a; this.b = b; } public double getArea() { return a*b; } } public class Applacation { public static void main(String[] args) { Pillar pillar; Geometry bottom; bottom = new Rectangle(3,4); pillar = new Pillar(bottom,5);//柱體兩個引數,一個為地面的面積,一個為高 System.out.println("地面為三角形的柱體體積為:"+pillar.getVolume()); bottom = new Circle(3); pillar = new Pillar(bottom,5); System.out.println("地面為圓形的柱體的體積為:"+pillar.getVolume()); } }