看代碼發(fā)現(xiàn)接口文件居然繼承兩個(gè)接口,想到一句話,“只能繼承一個(gè)類,可以實(shí)現(xiàn)多個(gè)接口”,然后就陷入疑問。經(jīng)度娘解釋:
java類是單繼承的。classB Extends classA
java接口可以多繼承。Interface3 Extends Interface0, Interface1, interface
補(bǔ)全知識(shí)點(diǎn):java類只能繼承(Extends)一個(gè)類,可以實(shí)現(xiàn)(implements)多個(gè)接口,java接口可以繼承(Extends)多個(gè)接口,不能實(shí)現(xiàn)(implements)任何接口
例子:
Interface1:
public?interface?Interface1?{??
????public?void?method1();??
}??
Interface2:
看到接口之間的關(guān)系使用implements關(guān)鍵字時(shí)會(huì)報(bào)錯(cuò),錯(cuò)誤提示信息如下:
Syntax?error?on?token?"implements",?extends?expected??
eclipse明確指出,接口之間是繼承關(guān)系,而非實(shí)現(xiàn)關(guān)系。
修改為extends時(shí)代碼正確:
public?interface?Interface2?extends?Interface1{??
????public?int?a?=?1;??
????public?void?method2();??
}??
代碼清單:
//interface3??
<pre?name="code"?class="java">public?interface?Interface3?{??
????public?void?method3();??
}??
//interface4
<pre?name="code"?class="java">public?interface?Interface4?extends?Interface1,?Interface3?{??
????public?void?method4();??
}??
實(shí)現(xiàn)類A:
public?class?A?implements?Interface4?{??
????public?static?void?main(String[]?args)?{??
????}??
????public?void?method1()?{??
????????//?TODO?Auto-generated?method?stub??
????????System.out.println("method1");??
????}??
????public?void?method3()?{??
????????//?TODO?Auto-generated?method?stub??
????????System.out.println("method2");??
????}??
????public?void?method4()?{??
????????//?TODO?Auto-generated?method?stub??
????????System.out.println("method3");??
????}??
}??
Main主類:
public?class?Main?{??
????public?static?void?main(String[]?args)?{??
????????//?TODO?Auto-generated?method?stub??
????????A?a?=?new?A();??
????????a.method1();??
????????a.method3();??
????????a.method4();??
????}??
}??
輸出結(jié)果:
method1??
method2??
method3??
說明java接口的繼承是多繼承的機(jī)制。
原文轉(zhuǎn)自:https://www.cnblogs.com/dengyungao/p/7524960.html