java Java如何调用祖父母的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2584377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:54:31  来源:igfitidea点击:

Java How to call method of grand parents?

javaoverridingsuper

提问by Arkaha

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

可能的重复:
为什么是 super.super.method(); 在 Java 中不允许?

Let's assume I have 3 classes A, Band C, each one extending the previous one.

假设我有3个班AB并且C,每一个延伸的前一个。

How do I call the code in A.myMethod()from C.myMethod()if Balso implements myMethod?

我如何A.myMethod()C.myMethod()if 中调用代码B也实现了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(); ??
  }
}

回答by Tom Hawtin - tackline

You can't. This is deliberate.

你不能。这是故意的。

Class Bprovides an interface (as in the concept, not the Java keyword) to subclasses. It has elected not to give direct access to the functionality of A.myMethod. If you require Bto provide that functionality, then use a different method for it (different name, make it protected). However, it is probably better to "prefer composition over inheritance".

ClassB为子类提供了一个接口(在概念中,而不是 Java 关键字)。它已选择不直接访问A.myMethod. 如果您需要B提供该功能,请为其使用不同的方法(不同的名称,make it protected)。但是,“更喜欢组合而不是继承”可能更好。

回答by Bozho

You can't, and you shouldn't.

你不能,也不应该。

This is a sign of bad design. Either rename a method or include the required common functionality in another method or an utility class.

这是不良设计的标志。重命名方法或在另一个方法或实用程序类中包含所需的通用功能。

回答by Daren Thomas

I'm not sure you can. Java makes all methods virtual by default. This means that the most simple solution will not work: Declare a variable of type A, assign your Cinstance to it and call myMethodwill result in C.myMethodbeing called.

我不确定你能不能。默认情况下,Java 使所有方法都是虚拟的。这意味着最简单的解决方案将不起作用:声明一个 type 变量A,将您的C实例分配给它, callmyMethod将导致C.myMethod被调用。

You could try to reflect type Aand invoke its methods directly. It would be interesting to see what happens in this case, but I'd be surprised if the virtual dispatch wouldn't happen...

您可以尝试反射类型A并直接调用其方法。看看在这种情况下会发生什么会很有趣,但如果虚拟调度不会发生,我会感到惊讶......