Search code examples
javainheritancesuperclass

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
    }
}

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)

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.


Solution

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

    Similar questions: