从头认识java-7.5 怎样通过继承扩展接口?

来源:互联网 发布:华南理工网络教育登录 编辑:程序博客网 时间:2024/06/03 20:47

我们这一章节来讨论一下怎样通过继承扩展接口。

接口跟类一样,具有继承的特性,但是他只是继承接口,不继承类。

package com.ray.ch07;interface WhatPersonCanDo {void run();void sleep();}interface WhatSingerCanDo extends WhatPersonCanDo {void sing();}class Singer implements WhatSingerCanDo {@Overridepublic void run() {// TODO Auto-generated method stub}@Overridepublic void sleep() {// TODO Auto-generated method stub}@Overridepublic void sing() {// TODO Auto-generated method stub}}


从上面的代码可以看出,WhatSingerCanDo继承了WhatPersonCanDo,使得Singer在实现WhatSingerCanDo接口的时候,需要重写三个方法。

 

虽然通过继承可以对接口进行扩展,但是,需要注意的是不同接口定义相同名称的方法这一混淆点。

因为不同的接口定义了相同标签的方法,而且看上去还是重写覆盖的样子,这个时候就会使得可读性大大降低。

当然,这一点可能在实际编程里面稍微少见,但是也是可能出现的注意点。

下面是一个错误的代码,无论怎么注释都是错误,下面注释里面注解了一些错误。

package com.ray.ch07;interface interface1 {void run();}interface interface2 {void run(int speed);}class father {public int run(int speed) {return speed;}}/** * The return types are incompatible for the inherited methods interface2.run(int), father.run(int) */class Test extends father implements interface1, interface2 {//error/** * Multiple markers at this line - The return type is incompatible with * father.run(int) - overrides com.ray.ch07.father.run - Duplicate method * run(int) in type Test */// @Override// public void run(int speed) {// }/** * Multiple markers at this line - The return type is incompatible with * interface2.run(int) - overrides com.ray.ch07.father.run */// @Override// public int run(int speed) {// }@Overridepublic void run() {}}


 

当然,出现上面的这种情形是非常少见的,因为现在大部分的编程人员都使用框架,而且都是单继承和单接口,但是我们还必须注意这点。

 

这一章节就到这里,谢谢。

-----------------------------------

目录


 

1 0