java 使用接口的好處


面向接口編程,提高程序的擴展性,這樣可以 開放擴展 關閉 修改,體現了開閉原則

代碼 如下

 

public interface TestInterface {
    public void print();
}

 

public class Print implements TestInterface{
    public void print(){
        System.out.println("Print.print");
    }

}

 

public class Print2 implements TestInterface{
    public void print(){
        System.out.println("Print.print2");
    }

}

 

public class Main {

    public static void main(String[] args) {
        Main m = new Main();
        Print p1 = new Print();
        m.MainTestinterface( p1 );
        Print2 p2 = new Print2();
        m.MainTestinterface( p2 );
    }

    public void MainTestinterface(TestInterface ti ){
        ti.print();
    }
}

輸出打印

Print.print
Print.print2

這段程序利用了 java 的多態特性 ,實現動態綁定 對象ti。父類的引用指向子類對象 

這樣 就不能修改MainTestinterface方法,遇到什么需求,只要增加 Print1 2 .. n 就可以實現了

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM