Java How to call method of grand parents? [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-18 03:50:55

问题


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

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

How do I call the code in A.myMethod() from C.myMethod() if B also implements 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(); ??
  }
}

回答1:


You can't. This is deliberate.

Class B provides 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 B to 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".




回答2:


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.




回答3:


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 C instance to it and call myMethod will result in C.myMethod being called.

You could try to reflect type A and 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...



来源:https://stackoverflow.com/questions/2584377/java-how-to-call-method-of-grand-parents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!