在Java中如果一個類同時繼承接口A與B,並且這兩個接口中具有同名方法,會怎麼樣?
動手做實驗:
1 interface A{ 2 void fun(); 3 } 4 interface B{ 5 void fun(); 6 } 7 interface C extends A,B{ 8 9 } 10 public class Test implements C{ 11 @Override 12 public void fun() { 13 System.out.println("hehe"); 14 } 15 16 public static void main(String[] args) { 17 new Test().fun(); 18 } 19 }
上例的情況,可以正常編譯運行,輸出"hehe",因爲A與B中的fun具有相同的簽名(參數個數與類型相同)
1 interface A{ 2 void fun(); 3 } 4 interface B{ 5 int fun(int x); 6 } 7 interface C extends A,B{ 8 9 } 10 public class Test implements C{ 11 @Override 12 public void fun() { 13 System.out.println("hehe"); 14 } 15 16 @Override 17 public int fun(int x) { 18 return 0; 19 } 20 21 public static void main(String[] args) { 22 new Test().fun(); 23 } 24 }
上例也是可以編譯運行的,因爲A與B中的fun方法具有不同的函數簽名,本質上是兩個方法,分別實現即可。
1 interface A{ 2 void fun(); 3 } 4 interface B{ 5 int fun(); 6 } 7 interface C extends A,B{ 8 9 } 10 public class Test implements C{ 11 @Override 12 public void fun() { 13 System.out.println("hehe"); 14 } 15 16 public static void main(String[] args) { 17 new Test().fun(); 18 } 19 }
而這種具有相同函數簽名,但不同返回值的方法,是沒有辦法編譯的,接口C便已經無法編譯。
在Java8中,接口可以具有默認的實現,這裏再舉幾個實例
1 interface A{ 2 default void fun() { 3 System.out.println("I am A"); 4 } 5 } 6 interface B{ 7 default void fun() { 8 System.out.println("I am B"); 9 } 10 } 11 interface C extends A,B{ 12 @Override 13 default void fun() { 14 System.out.println("I am C"); 15 } 16 } 17 public class Test implements C{ 18 19 public static void main(String[] args) { 20 new Test().fun(); 21 } 22 }
上例將輸出"I am C",因爲接口C給出了fun的默認實現
1 interface A{ 2 default void fun() { 3 System.out.println("I am A"); 4 } 5 } 6 interface B{ 7 default void fun() { 8 System.out.println("I am B"); 9 } 10 } 11 interface C extends A,B{ 12 @Override 13 void fun(); 14 } 15 public class Test implements C{ 16 @Override 17 public void fun() { 18 C.super.fun(); 19 } 20 21 public static void main(String[] args) { 22 new Test().fun(); 23 } 24 }
上例將產生編譯錯誤,因爲C中對fun方法進行了覆蓋,C的fun是抽象的,在第18行將產生無法訪問C中抽象方法fun的編譯錯誤。
1 interface A{ 2 default void fun() { 3 System.out.println("I am A"); 4 } 5 } 6 interface B{ 7 default void fun() { 8 System.out.println("I am B"); 9 } 10 } 11 interface C extends A,B{ 12 @Override 13 default void fun() { 14 A.super.fun(); 15 } 16 } 17 public class Test implements C{ 18 19 public static void main(String[] args) { 20 new Test().fun(); 21 } 22 }
接口C爲fun方法指定爲接口A中的實現,程序輸出"I am A"