核心是使用上转型对象,将abstract类声明的对象作为其子类对象的上转型对象,使上转型对象可以调用子类重写的方法.
使得设计一个需求多变的类时,不该让类面向具体实现的类,而是面向抽象类,即用抽象类来声明所有的可实现的方法.
具体代码为:
public abstract class Geometry {
public abstract double getArea();
}
//Pollar类
public class Pillar {
Geometry bottom;
double height;
Pillar (Geometry bottom, double height){
this.bottom = bottom;this.height = height;
}
public double getVolume(){
if(bottom==null){
return -1;
}
return bottom.getArea()*height;//bottom可以调用子类重写的getArea方法
}
}
//Circle类
public class Circle extends Geometry{
double r;
Circle (double r){
this.r = r;}
public double getArea(){
return(3.14*r*r)}
}
}
public class application{
public static void main(String args[]){
Pillar pillar;
Geometry bottom =null;
bottom = new Circle();//抽象类转换成上转型对象以用来实现具体类
pillar.(bottom,20);
System.out.println("体积"+pillar.getVolume)
}
}