接口中的默認方法與靜態方法

在Java8之前的版本中,接口中只能聲明常量和抽象方法,接口的實現類中必須實現接口中所有的抽象方法。而在Java8中,接口中可以聲明默認方法靜態方法。

接口中的默認方法

Java 8中允許接口中包含具有具體實現的方法,該方法稱為“默認方法”,默認方法使用“ default ”關鍵字修飾 。

示例:

public interface MyInterface {
    default String getMsg(String srcMsg){
        return "======"+srcMsg;
    }
}

接口中的默認方法,有一個“類優先”原則:

若一個接口中定義了一個默認方法,而另外一個父類或接口中又定義了同一個同名的方法時:

  • 選擇父類中的方法。如果一個父類提供了具體的實現,那麼接口中具有相同名稱的參數的默認方法會被忽略。
  • 接口衝突。如果一個父接口提供一個默認方法,而另一個接口中也提供了一個具有相同名稱和參數列表的方法(不管方法是否是默認方法),那麼必須覆蓋該方法來解決衝突。

示例1:

public interface MyInterface1 {
    default String getMsg(String srcMsg){
        return "===我是MyInterface1111111==="+srcMsg;
    }
}
///////////////////////////////////////////////////////
public class MyClass1 {
    public String getMsg(String srcMsg){
        return "===我是MyClass11111==="+srcMsg;
    }
}
///////////////////////////////////////////////////////
public class MySubClass1 extends MyClass1 implements MyInterface1 {
}

///////////////////////////////////////////////////////
public class InterfaceTest {

    public static void main(String[] args) {
        MySubClass1 ms1 = new MySubClass1();

        String srcMsg = "Java 牛逼!!";
        //MySubClass1 類繼承了 MyClass1 類,實現了MyInterface1 接口,根據類優先原則,調用同名方法時,會忽略掉接口 MyInterface1 中的默認方法。
        System.out.println(ms1.getMsg(srcMsg));//輸出結果:===我是MyClass11111===Java 牛逼!!

    }
}

示例2:

public interface MyInterface2 {
    default String getMsg(String srcMsg){
        return "===我是MyInterface2222222==="+srcMsg;
    }
}
////////////////////////////////////////////////////////////////
public class MySubClass2 implements MyInterface1,MyInterface2 {
    @Override
    public String getMsg(String srcMsg) {
        //同時實現了 MyInterface1,MyInterface2  接口,根據 類優先 原則,兩個父接口中都提供了相同的方法,那麼子類中就必須重寫這個方法來解決衝突。
        return MyInterface1.super.getMsg(srcMsg);
        //return MyInterface2.super.getMsg(srcMsg);
        //return "------"+srcMsg;
    }
}
////////////////////////////////////////////////////////////////
public class InterfaceTest {

    public static void main(String[] args) {
        MySubClass2 ms2 = new MySubClass2();

        //MySubClass2 重新實現了兩個父接口中都存在的相同名稱的方法。
        System.out.println(ms2.getMsg(srcMsg));//輸出結果:===我是MyInterface1111111===Java 牛逼!!
    }
}

 

接口中的靜態方法

在Java8中,接口中允許添加 靜態方法,使用方式:“接口名.方法名”

示例:

public interface MyInterface3 {
    static String getMsg(String msg){
        return "我是接口中的靜態方法:"+msg;
    }

    static void main(String[] args) {
        System.out.println(MyInterface3.getMsg("Java牛逼!!"));
    }
}

 

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計公司推薦不同的風格,搶佔消費者視覺第一線

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

※自行創業缺乏曝光? 網頁設計幫您第一時間規劃公司的形象門面

南投搬家公司費用需注意的眉眉角角,別等搬了再說!

新北清潔公司,居家、辦公、裝潢細清專業服務

※教你寫出一流的銷售文案?