淺談Java 繼承接口同名函數(shù)問(wèn)題
在Java中如果一個(gè)類(lèi)同時(shí)繼承接口A與B,并且這兩個(gè)接口中具有同名方法,會(huì)怎么樣?
動(dòng)手做實(shí)驗(yàn):
interface A{ void fun();}interface B{ void fun();}interface C extends A,B{ }public class Test implements C{ @Override public void fun() { System.out.println('hehe'); } public static void main(String[] args) { new Test().fun(); }}
運(yùn)行截圖:

上例的情況,可以正常編譯運(yùn)行,輸出'hehe',因?yàn)锳與B中的fun具有相同的簽名(參數(shù)個(gè)數(shù)與類(lèi)型相同)
interface A{ void fun();}interface B{ int fun(int x);}interface C extends A,B{ }public class Test implements C{ @Override public void fun() { System.out.println('hehe1'); } @Override public int fun(int x) { return 0; } public static void main(String[] args) { new Test().fun(); }}

上例也是可以編譯運(yùn)行的,因?yàn)锳與B中的fun方法具有不同的函數(shù)簽名,本質(zhì)上是兩個(gè)方法,分別實(shí)現(xiàn)即可。
interface A{ void fun();}interface B{ int fun();}interface C extends A,B{ }public class Test implements C{ @Override public void fun() { System.out.println('hehe'); } public static void main(String[] args) { new Test().fun(); }}

而這種具有相同函數(shù)簽名,但不同返回值的方法,是沒(méi)有辦法編譯的,接口C便已經(jīng)無(wú)法編譯。
補(bǔ)充知識(shí):java 類(lèi)implements多個(gè)接口含有相同名字函數(shù)
java 類(lèi)不能多繼承 class A extends B,C{}是不允許的
但能實(shí)現(xiàn)多個(gè)接口 class A implements B,C{}是可以的,而多個(gè)接口中如果出現(xiàn)相同名字函數(shù):
interface in1{ public void fun1(); public void fun2();}interface in2{ public void fun1(); public void fun3();}
只許實(shí)現(xiàn)一個(gè)即可:
class fun implements in1,in2{ public void fun3() { // TODO Auto-generated method stub } public void fun1() { // TODO Auto-generated method stub } public void fun2() { // TODO Auto-generated method stub }}
以上這篇淺談Java 繼承接口同名函數(shù)問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法2. 解析原生JS getComputedStyle3. idea修改背景顏色樣式的方法4. IntelliJ IDEA刪除類(lèi)的方法步驟5. VMware中如何安裝Ubuntu6. Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)7. idea設(shè)置代碼格式化的方法步驟8. idea打開(kāi)多個(gè)窗口的操作方法9. IntelliJ IDEA調(diào)整字體大小的方法10. 使用IDEA編寫(xiě)jsp時(shí)EL表達(dá)式不起作用的問(wèn)題及解決方法

網(wǎng)公網(wǎng)安備