是继承还是实现
首先要搞清楚接口之间的关系使用的关键字是extends还是implement。网友有如下回答:
一个类只能extends一个父类,但可以implements多个接口。java通过使用接口的概念来取代C++中多继承。与此同时,一个接口则可以同时extends多个接口,却不能implements任何接口。因而,Java中的接口是支持多继承的。
自己动手验证了一下:
首先在eclipse中创建interface时,弹出选项窗口中会有一个选项:
可以看到eclipse中也明确提示可以使用extends关键字继承上层接口。
再看测试代码清单:
Interface1:
[java]
view plain
copy
public interface Interface1 {
public void method1(); }
Interface2:
看到接口之间的关系使用implements关键字时会报错,错误提示信息如下:
[html]
view plain
copy
Syntax error on token "implements", extends expected
eclipse明确指出,接口之间是继承关系,而非实现关系。
修改为extends时代码正确:
[java]
view plain
copy
public interface Interface2
extends Interface1{
public int a =
1;
public void method2(); }
前面网友又提到java接口是课可以支持多继承的。做了一下实验:
代码清单:
[java]
view plain
copy
[java]
view plain
copy
<pre name=
"code" class=
"java">
public interface Interface3 {
public void method3(); }
//interface4
[java]
view plain
copy
<pre name=
"code" class=
"java">
public interface Interface4
extends Interface1, Interface3 {
public void method4(); }
实现类A:
[java]
view plain
copy
public class A
implements Interface4 {
public static void main(String[] args) { }
@Override public void method1() { System.out.println(
"method1"); }
@Override public void method3() { System.out.println(
"method2"); }
@Override public void method4() { System.out.println(
"method3"); } }
Main主类:
[java]
view plain
copy
public class Main {
public static void main(String[] args) { A a =
new A(); a.method1(); a.method3(); a.method4(); } }
输出结果:
[html]
view plain
copy
method1 method2 method3
说明java接口的继承是多继承的机制。
如果让普通类去继承接口
1会让把普通类改为接口
2会让把继承改为实现
转载来源:http://blog.csdn.net/u010921701/article/details/52830779