我有一个接口(interface) z。它是由y类实现的。我有另一个继承类 y 的类 x。由于 y 实现了类 z 指定的契约,因此 x 也执行相同的操作,因为它扩展了类 y。因此它也应该实现接口(interface) z 吗?
最佳答案
没有。如果该接口(interface)是在当前类的层次结构中的某个位置实现的,那么这就足够了。
最后,接口(interface)只是定义了类应该包含的一些方法。对于您的子类来说,这与顶级类中的“正常”方法没有什么不同。
示例:
public class Main {
public static void main(String[] args) {
new X().test();
new Y().test();
}
}
class X extends Y{
}
class Y implements Z{
@Override
public void test() {
System.out.println("in Y");
}
}
interface Z {
public void test();
}
这将简单地输出
in Y
in Y
如果我们将X
的定义更改为
class X extends Y implements Z
然后代码仍然可以毫无问题地编译,输出保持不变。
如果我们在 X
中实现此方法,那么我们将从 Y
中隐藏该方法实现。
关于java - 扩展类 y(实现接口(interface) z)的 java 类 x 是否也应该实现接口(interface) z,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22174586/