在多级继承中从子类调用“大"父函数 [英] Call 'grand' parent function from child class in multi-level inheritance

查看:38
本文介绍了在多级继承中从子类调用“大"父函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
    }
}

类似问题:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆