面试题答案
一键面试接口继承的语法规则
在Java中,一个接口可以通过extends
关键字继承另一个接口。语法如下:
public interface SubInterface extends SuperInterface {
// 子接口中可以定义新的抽象方法等
}
如果要继承多个接口,使用逗号分隔多个接口名,例如:
public interface SubInterface extends Interface1, Interface2, Interface3 {
// 子接口内容
}
一个接口继承多个接口时可能面临的潜在问题及解决方法
- 方法冲突问题:当继承的多个接口中存在签名相同(方法名、参数列表相同)的默认方法时,会产生冲突。
- 解决方法:
- 在子接口中重新声明这个冲突的方法,但是不提供方法体,让实现该子接口的类去实现这个方法。例如:
- 解决方法:
interface Interface1 {
default void method() {
System.out.println("Interface1's method");
}
}
interface Interface2 {
default void method() {
System.out.println("Interface2's method");
}
}
interface SubInterface extends Interface1, Interface2 {
@Override
void method();
}
class ImplementingClass implements SubInterface {
@Override
public void method() {
System.out.println("ImplementingClass's implementation");
}
}
- 在子接口中提供自己的默认实现来覆盖冲突的默认方法。例如:
interface Interface1 {
default void method() {
System.out.println("Interface1's method");
}
}
interface Interface2 {
default void method() {
System.out.println("Interface2's method");
}
}
interface SubInterface extends Interface1, Interface2 {
@Override
default void method() {
System.out.println("SubInterface's implementation");
}
}
- 命名冲突问题:如果继承的多个接口中定义了相同名称的常量,也会产生冲突。
- 解决方法:在使用该常量时通过接口名进行限定,或者在子接口中重新定义一个不同名称的常量来替代。例如:
interface InterfaceA {
int VALUE = 10;
}
interface InterfaceB {
int VALUE = 20;
}
interface SubInterface extends InterfaceA, InterfaceB {
int NEW_VALUE = 30;
}
class Main {
public static void main(String[] args) {
// 通过接口名限定
System.out.println(InterfaceA.VALUE);
System.out.println(InterfaceB.VALUE);
// 使用新定义的常量
System.out.println(SubInterface.NEW_VALUE);
}
}