应用 :求面积
1,抽象类 Geometry .
public abstract class Geometry { public abstract double getArea(); }
2,矩形 Rect
public class Rect extends Geometry{ double a,b; Rect(double a,double b){ this.a = a; this.b = b; } @Override public double getArea() { return a*b; } }
3,圆形 Circle
public class Circle extends Geometry{ double r; public Circle(double r) { this.r = r; } @Override public double getArea() { // TODO Auto-generated method stub return 3.14*r*r; } }
4, 数组存模 , 使用抽象方法 。 求面积和 (注入灵魂)
public class TotalArea { double area(Geometry ...p) { double sum = 0; for (int i = 0; i < p.length; i++) { sum += p[i].getArea(); } return sum; } }
5 , 主类 Main
public class Main { public static void main(String[] args) { TotalArea t = new TotalArea(); double area = t.area(new Rect(2, 3),new Circle(5.2),new Circle(12)); System.out.printf("面积和: ",area); } }