Java 8新特性三:Default Methods And Static Methods

關注:Java提高營,最新文章第一時間送達,10T 免費學習資料隨時領取!!!java

Default Methods

在Java 8以前,接口只能定義抽象方法。這些方法的實現必須在單獨的類中提供。所以,若是要在接口中添加新方法,則必須在實現接口的類中提供其實現代碼。爲了克服此問題,Java 8引入了默認方法的概念,容許接口定義具備實現體的方法,而不會影響實現接口的類。bash

// A simple program to Test Interface default 
// methods in java 
interface TestInterface { 
    // abstract method 
    public void square(int a); 
  
    // default method 
    default void show() { 
      System.out.println("Default Method Executed"); 
    } 
} 
  
class TestClass implements TestInterface { 
    // implementation of square abstract method 
    public void square(int a) { 
        System.out.println(a*a); 
    } 
  
    public static void main(String args[]) { 
        TestClass d = new TestClass(); 
        d.square(4); 
  
        // default method executed 
        d.show(); 
    } 
} 

複製代碼

輸出:學習

16
 Default Method Executed
複製代碼

引入默認方法能夠提供向後兼容性,以便現有接口能夠使用lambda表達式,而無需在實現類中實現這些方法。spa

Static Methods

接口也能夠定義靜態方法,相似於類的靜態方法code

// A simple Java program to TestClassnstrate static 
// methods in java 
interface TestInterface { 
    // abstract method 
    public void square (int a); 
  
    // static method 
    static void show() { 
        System.out.println("Static Method Executed"); 
    } 
} 
  
class TestClass implements TestInterface { 
    // Implementation of square abstract method 
    public void square (int a) { 
        System.out.println(a*a); 
    } 
  
    public static void main(String args[]) { 
        TestClass d = new TestClass(); 
        d.square(4); 
  
        // Static method executed 
        TestInterface.show(); 
    } 
} 
複製代碼

輸出:blog

16
 Static Method Executed
複製代碼

默認方法和多重繼承

若是一個類實現了多個接口且這些接口中包含了同樣的方法簽名,則實現類須要顯式的指定要使用的默認方法,或者應重寫默認方法繼承

// A simple Java program to demonstrate multiple 
// inheritance through default methods. 
interface TestInterface1 { 
    // default method 
    default void show() { 
        System.out.println("Default TestInterface1"); 
    } 
} 
  
interface TestInterface2 { 
    // Default method 
    default void show() { 
        System.out.println("Default TestInterface2"); 
    } 
} 
  
// Implementation class code 
class TestClass implements TestInterface1, TestInterface2 { 
    // Overriding default show method 
    public void show() { 
        // use super keyword to call the show 
        // method of TestInterface1 interface 
        TestInterface1.super.show(); 
  
        // use super keyword to call the show 
        // method of TestInterface2 interface 
        TestInterface2.super.show(); 
    } 
  
    public static void main(String args[]) { 
        TestClass d = new TestClass(); 
        d.show(); 
    } 
} 
複製代碼

輸出:接口

Default TestInterface1
Default TestInterface2
複製代碼

總結

  1. 從Java 8開始,接口能夠定義具備實現的默認方法
  2. 接口也能夠定義靜態方法,相似於類中的靜態方法。
  3. 引入默認方法以提供對舊接口的向後兼容性,以便它們能夠使用新方法而不會影響現有代碼。
相關文章
相關標籤/搜索