在多级继承中从子类调用“大"父函数 [英] Call 'grand' parent function from child class in multi-level inheritance
问题描述
public class GrandParent
{
public void walk()
{
...
}
}
public class Parent
{
public void walk()
{
...
}
}
public class Child
{
public void walk()
{
// Here in some cases I want to use walk method of GrandParent class
}
}
现在在 Child.walk() 中,我只想在某些情况下使用 GrandParent.walk().我怎样才能做到这一点?由于 super.walk() 将始终使用 Parent.walk().
Now in Child.walk(), I want to use GrandParent.walk() only in some cases. How can I do that? Since super.walk() will always use Parent.walk().
注意:(请注意,这是复杂场景的简化示例)
NOTE: (Please note that this is simplified example of a complex scenario)
注意 2: 请仅说明是否有标准程序来执行此操作.我在父类中使用了一个标志,如果孩子想使用 GrandParent 的方法,它会设置这个标志.但是这个序列变得非常复杂.
NOTE2: Please only tell if there is a standard procedure of doing that. I have used a flag in parent class, which the child sets if it wants to use the method of GrandParent. But this sequence becomes very complex.
推荐答案
您可以像这样指定访问父值的方法:
You could specify method for accessing parent's value like this:
public class GrandParent
{
public void walk()
{
...
}
}
public class Parent
{
public void walk()
{
...
}
public void grandParentWalk()
{
super.walk();
}
}
public class Child
{
public void walk()
{
grandParentWalk();
}
}
类似问题:
- Java:你好吗访问向下两级的父类方法?
- 为什么是 super.super.method();Java 中不允许?
这篇关于在多级继承中从子类调用“大"父函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!