gpt4 book ai didi

Java如何调用祖 parent 的方法?

转载 作者:IT老高 更新时间:2023-10-28 20:29:29 26 4
gpt4 key购买 nike

Possible Duplicate:
Why is super.super.method(); not allowed in Java?

假设我有 3 个类 ABC,每个类都扩展了前一个。

如果 B 也实现 myMethod,我如何从 C.myMethod() 调用 A.myMethod() 中的代码?

class A
{
public void myMethod()
{
// some stuff for A
}
}

class B extends A
{
public void myMethod()
{
// some stuff for B
//and than calling A stuff
super.myMethod();
}
}

class C extends B
{
public void myMethod()
{
// some stuff for C
// i don't need stuff from b, but i need call stuff from A
// something like: super.super.myMethod(); ?? how to call A.myMethod(); ??
}
}

最佳答案

你不能。这是故意的。

Class B 为子类提供接口(interface)(在概念中,不是Java 关键字)。它已选择不直接访问 A.myMethod 的功能。如果您需要 B 来提供该功能,请使用不同的方法(不同的名称,使其 protected)。但是,“优先组合胜过继承”可能更好。

关于Java如何调用祖 parent 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2584377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com