面向抽象编程

abstract类中的abstract方法只允许声明,比允许实现,要实现抽象方法必须将abstract类的对象转变为abstract类的子类的上转型对象。

实例分析:

Geometry抽象类:
package zjl.java;
public abstract class Geometry {
    public String name;
    public abstract double getArea();
}
Circle子类:
package zjl.java;

public class Circle extends Geometry{
    double r;
    Circle(double r,String s){
        this.r = r;
        this.name = s;
    }
    public double getArea(){
        return 3.14*r*r;
    }
}
Rectanger子类:
package zjl.java;

public class Rectanger extends Geometry{
    double a,b;
    public Rectanger(double a,double b,String s) {
        this.a = a;
        this.b = b;
        this.name = s;
    }
    public double getArea(){
        return a*b;
    }
}
Pillar类:
package zjl.java;
public class Pillar {
    Geometry bottom;
    double height;
    Pillar(Geometry botton,double height){
        this.bottom = botton;
        this.height = height;
    }
    public double getVolume(){
        return bottom.getArea()*height;
    }
}

主类:

package zjl.java;

public class TestAbstractProgram {

    public static void main(String[] args) {
        Pillar pillar;
        Circle circle = new Circle(2.3,"circle");
        Rectanger rectanger = new Rectanger(1.2, 2.9,"rectanger");
        Geometry bottom;
        //botton = new Geometry();       //abstract 类不能用new 创建对象
        bottom = circle;
        pillar = new Pillar(bottom, 10);
        System.out.println(bottom.name + "'s volume is "+ pillar.getVolume());
        bottom = rectanger;
        pillar = new Pillar(bottom, 10);
        System.out.println(bottom.name + "'s volume is "+pillar.getVolume());
    }

}

运行结果:

circle's volume is 166.106
rectanger's volume is 34.8

posted on 2016-04-06 12:03  Tob's_the_top  阅读(258)  评论(0编辑  收藏  举报

导航