java 一個(gè)類(lèi)實(shí)現(xiàn)兩個(gè)接口的案例
直接用英文逗號(hào)分隔就可以了,比如:
inerface IHello { String sayHello(String name); }interface IHi { String sayHi(String name); } class ServiceImpl implements IHello, IHi {// 實(shí)現(xiàn)三個(gè)四個(gè)。。。n個(gè)接口都是使用逗號(hào)分隔public String sayHello(String name) { return 'Hello, ' + name; }public String sayHi(String name) { return 'Hi, ' + name; }}
補(bǔ)充知識(shí):Java 一個(gè)類(lèi)實(shí)現(xiàn)的多個(gè)接口,有相同簽名的default方法會(huì)怎么辦?
看代碼吧~
public interface A { default void hello() { System.out.println('Hello from A'); }}public interface B extends A { default void hello() { System.out.println('Hello from B'); }}public class C implements B, A { public static void main(String... args) { new C().hello(); }}
這段代碼,會(huì)打印什么呢?
有三條規(guī)則
類(lèi)永遠(yuǎn)贏。類(lèi)聲明的方法,或者超類(lèi)聲明的方法,比default方法的優(yōu)先級(jí)高
否則,子接口贏
否則,如果集成自多個(gè)接口,必須明確選擇某接口的方法
上面代碼的UML圖如下
所以,上面的代碼,輸出是
Hello from B
如果這樣呢?
public class D implements A{ }public class C extends D implements B, A { public static void main(String... args) { new C().hello(); }}
UML圖是這樣的
規(guī)則1說(shuō),類(lèi)聲明的方法優(yōu)先級(jí)高,但是,D沒(méi)有覆蓋hello方法,它只是實(shí)現(xiàn)了接口A。所以,它的default方法來(lái)自接口A。規(guī)則2說(shuō),如果類(lèi)和超類(lèi)沒(méi)有方法,就是子接口贏。所以,程序打印的還是“Hello from B”。
所以,如果這樣修改代碼
public class D implements A{ void hello(){ System.out.println('Hello from D'); }}public class C extends D implements B, A { public static void main(String... args) { new C().hello(); }}
程序的輸出就是“Hello from D”。
如果D這樣寫(xiě)
public abstract class D implements A { public abstract void hello();}
C就只能實(shí)現(xiàn)自己的抽象方法hello了。
如果是這樣的代碼呢
public interface A { default void hello() { System.out.println('Hello from A'); }}public interface B { default void hello() { System.out.println('Hello from B'); }}public class C implements B, A { }
UML圖如下
會(huì)生成這樣的編譯器錯(cuò)誤
'Error: class C inherits unrelated defaults for hello() from types B and A.'
怎么修改代碼呢?只能明確覆蓋某接口的方法
public class C implements B, A { void hello(){ B.super.hello(); }}
如果代碼是這樣的,又會(huì)怎樣呢?
public interface A{ default void hello(){ System.out.println('Hello from A'); }}public interface B extends A { }public interface C extends A { }public class D implements B, C { public static void main(String... args) { new D().hello(); }}
UML圖是這樣的
很明顯,還是不能編譯。
以上這篇java 一個(gè)類(lèi)實(shí)現(xiàn)兩個(gè)接口的案例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解CSS偽元素的妙用單標(biāo)簽之美2. XML入門(mén)的常見(jiàn)問(wèn)題(四)3. ASP基礎(chǔ)知識(shí)VBScript基本元素講解4. 利用CSS3新特性創(chuàng)建透明邊框三角5. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼6. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法7. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式8. HTML5 Canvas繪制圖形從入門(mén)到精通9. XHTML 1.0:標(biāo)記新的開(kāi)端10. JSP的Cookie在登錄中的使用
