java 一個(gè)類實(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è)類實(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ī)則
類永遠(yuǎn)贏。類聲明的方法,或者超類聲明的方法,比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ō),類聲明的方法優(yōu)先級(jí)高,但是,D沒(méi)有覆蓋hello方法,它只是實(shí)現(xiàn)了接口A。所以,它的default方法來(lái)自接口A。規(guī)則2說(shuō),如果類和超類沒(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這樣寫
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è)類實(shí)現(xiàn)兩個(gè)接口的案例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. html清除浮動(dòng)的6種方法示例2. JavaScript數(shù)據(jù)類型對(duì)函數(shù)式編程的影響示例解析3. 利用CSS3新特性創(chuàng)建透明邊框三角4. 詳解CSS偽元素的妙用單標(biāo)簽之美5. div的offsetLeft與style.left區(qū)別6. CSS代碼檢查工具stylelint的使用方法詳解7. 使用css實(shí)現(xiàn)全兼容tooltip提示框8. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)9. vue實(shí)現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細(xì)教程10. 不要在HTML中濫用div
