接口扩展
在 Java 中,一个类去继承多个类是被禁止的,但是一个类却可以通过 implements 关键字去实现多个接口,就像下面这段代码:
public class Children implements CanEat, CanPlay {
@Override
public void eat() {
System.out.println("I can eat");
}
@Override
public void play() {
System.out.println("I can play");
}
}
interface CanEat {
void eat();
}
interface CanPlay {
void play();
}
/**
* 测试类
*/
class Test{
public static void test(CanEat canEat){
canEat.eat();
}
public static void test(CanPlay canPlay){
canPlay.play();
}
public static void main(String[] args) {
//创建 Children 对象
Children children = new Children();
//向上转型
eatTest(children);
playTest(children);
}
}
一个类可以实现任意多个接口,但是相应的,也要实现所有接口的抽象方法。同时上面的例子也展示了使用接口的原因,首先是实现类可以向上转型为多个父类(接口),代码更灵活;其次就是防止程序猿直接创建该接口的对象。
我们知道类可以继承,接口也是可以继承的,不仅可以,还能多继承,代码如下:
interface Animal {
void run();
}
interface Insect {
void fly();
}
/**
* 同时继承两个接口
*/
interface Butterfly extends Animal, Insect {
}
class BeautyButterfly implements Butterfly {
@Override
public void run() {
}
@Override
public void fly() {
}
}
我们可以看到,Butterfly 接口同时继承了两个接口,同时也继承了这两个接口中的抽象方法,所以实现 Butterfly 接口的类都要去实现 Animal 接口和 Insect 接口中的方法。这里我们就需要注意一下,在接口扩展的时候,我们应该避免在接口中使用相同的方法名,这种操作往往造成不可预知的混乱,同时也会报错。
public interface Butterfly extends Animal, Insect {
}
interface Animal {
void eat();
}
interface Insect {
//将这个方法的返回类型改为 int
int eat();
}
猜猜上述代码会发生什么,没错,编译器直接报错,提示方法冲突,简单粗暴。
接口可以嵌套在其他的接口中,比如这段代码:
public interface A {
void a();
/**
* 在接口 A 内创建接口 B
*/
interface B {
void b ();
}
}
/**
* 接口 A 实现类
*/
class AImpl implements A {
@Override
public void a() {
}
}
/**
* 接口 B 实现类
*/
class ABImpl implements A.B {
@Override
public void b() {
}
}
class InterfaceTest {
public static void main(String[] args) {
//创建 A d对象
A a = new AImpl();
//创建 B 对象
A.B b = new ABImpl();
}
}
上述代码在接口 A 中创建了接口 B,同时由于接口的特点,接口中所有的元素都必须是 public 的,所以 A 中的接口 B,自动就是 public 的,并且不能在一个接口内部声明 private 的接口,属性和方法,因为编译器直接报错:“Modifier ‘private’ not allowed here”。