为什么用抽象类

为什么要使用抽象类 ?

    父类是打印机, 子类是 喷墨打印机 和 针式打印机

    父类的 print 函数, 由于 喷墨打印机 和 针式打印机 原理不同而无法编写, 故应使用抽象函数

   

    下面演示一种抽象类的价值.

    

abstract class Printer{
    void Open(){
        System.out.println("Open");
    }
    
    void Close(){
        System.out.println("Close");
    }
    
    abstract void Print(String s){
    }
}
class HPPrinter extends Printer{
}
class CannonPrinter extends Printer{
    void Close(){
        this.Clean();
        super.Close();
    }
        
    void Clean(){
        System.out.println("Clean");
    }
}
class Test{
    public static void main(String args []){
        int flag = 1;
        
        if( flag == 0){
            HPPrinter hpprinter = new HPPrinter();
            hpprinter.Open();
            hpprinter.Print("abc");
            hpprinter.Close();
        }
        else if( flag == 1){
            CannonPrinter cannonprinter = new CannonPrinter();
            cannonprinter.Open();
            cannonprinter.Print("123");
            cannonprinter.Close();
        }
    }
}

   

     如果在父类中无法写出一个函数让所有子类适用, 最好的方法就是写成抽象类

     强制子类中对抽象函数进行复写, 这样可以大大减小代码的出错!

posted @ 2014-05-19 16:37  Mirrorhanman  阅读(268)  评论(0编辑  收藏  举报