企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### [结合接口时的命名冲突](https://lingcoder.gitee.io/onjava8/#/book/10-Interfaces?id=%e7%bb%93%e5%90%88%e6%8e%a5%e5%8f%a3%e6%97%b6%e7%9a%84%e5%91%bd%e5%90%8d%e5%86%b2%e7%aa%81) 当实现多个接口时可能会存在一个小陷阱。在前面的例子中,**CanFight**和**ActionCharacter**具有完全相同的`fight()`方法。完全相同的方法没有问题,但是如果它们的签名或返回类型不同会怎么样呢?这里有一个例子: ~~~ // interfaces/InterfaceCollision.java interface I1 { void f(); } interface I2 { int f(int i); } interface I3 { int f(); } class C { public int f() { return 1; } } class C2 implements I1, I2 { @Override public void f() {} @Override public int f(int i) { return 1; // 重载 } } class C3 extends C implements I2 { @Override public int f(int i) { return 1; // 重载 } } class C4 extends C implements I3 { // 完全相同,没问题 @Override public int f() { return 1; } } // 方法的返回类型不同 //- class C5 extends C implements I1 {} //- interface I4 extends I1, I3 {} ~~~ 覆写、实现和重载令人不快地搅和在一起带来了困难。同时,重载方法仅根据返回类型是区分不了的。当不注释最后两行时,报错信息如下: ~~~ error: C5 is not abstract and does not override abstract method f() in I1 class C5 extends C implements I1 {} error: types I3 and I1 are incompatible; both define f(), but with unrelated return types interfacce I4 extends I1, I3 {} ~~~ 当打算组合接口时,在不同的接口中使用相同的方法名通常会造成代码可读性的混乱,尽量避免这种情况。