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. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題2. 什么是python的自省3. Springboot Druid 自定義加密數(shù)據(jù)庫(kù)密碼的幾種方案4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)5. 詳解Android studio 動(dòng)態(tài)fragment的用法6. Vuex localStorage的具體使用7. php模擬實(shí)現(xiàn)斗地主發(fā)牌8. IntelliJ IDEA安裝插件的方法步驟9. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)10. 使用Android studio查看Kotlin的字節(jié)碼教程

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