原创
以下内容来自《Java 2实用教程》,主编:耿祥义、张跃平
鉴于面向抽象编程和面向接口编程思维培养的重要性,写此博客巩固。
面向抽象编程:
Circle.java
1 public class Circle { 2 double r; 3 Circle(double r){ 4 this.r=r; 5 } 6 public double getArea() { 7 return(3.14*r*r); 8 } 9 }
Pillar.java
1 public class Pillar { 2 Circle bottom; //bottom是用具体类Circle声明的对象 3 double height; 4 Pillar (Circle bottom,double height){ 5 this.bottom=bottom; 6 this.height=height; 7 } 8 public double getVolume() { 9 return bottom.getArea()*height; 10 } 11 }
Geometry.java
1 public abstract class Geometry { 2 public abstract double getArea(); 3 }
Pillar.java
1 public class Pillar { 2 Geometry bottom; //bottom是抽象类Geometry声明的变量 3 double height; 4 Pillar (Geometry bottom,double height){ 5 this.bottom=bottom; 6 this.height=height; 7 } 8 public double getVolume() { 9 if(bottom==null) { 10 System.out.println("没有底,无法计算体积"); 11 return -1; 12 } 13 return bottom.getArea()*height; //bottom可以调用子类重写的getArea方法 14 } 15 }
Circle.java
1 public class Circle extends Geometry{ 2 double r; 3 Circle(double r){ 4 this.r=r; 5 } 6 public double getArea() { 7 return(3.14*r*r); 8 } 9 }
Rectangle.java
1 public class Rectangle { 2 double a,b; 3 Rectangle(double a,double b){ 4 this.a=a; 5 this.b=b; 6 } 7 public double getArea() { 8 return a*b; 9 } 10 }
Application.java
1 public class Application { 2 public static void main(String args[]) { 3 Pillar pillar; 4 Geometry bottom=null; 5 pillar = new Pillar(bottom,100); //null底的柱体 6 System.out.println("体积"+pillar.getVolume()); 7 bottom=new Rectangle(12,22); 8 pillar=new Pillar(bottom,58); //pillar是具有矩形底的柱体 9 System.out.println("体积"+pillar.getVolume()); 10 bottom=new Circle(10); 11 pillar =new Pillar (bottom,58); //pillar是具有圆形底的柱体 12 System.out.println("体积"+pillar.getVolume()); 13 } 14 }
面向接口编程:
19:17:05
2018-07-07