Search code examples
c#oopinheritancemultiple-inheritance

Calling a Method from "base.base" class?


"Assume the following code:

public class MultiplasHerancas
{
    static GrandFather grandFather = new GrandFather();
    static Father father = new Father();
    static Child child = new Child();

    public static void Test() 
    {
        grandFather.WhoAreYou();
        father.WhoAreYou();
        child.WhoAreYou();

        GrandFather anotherGrandFather = (GrandFather)child;
        anotherGrandFather.WhoAreYou(); // Writes "I am a child"
    }

}

public class GrandFather
{
    public virtual void WhoAreYou() 
    {
        Console.WriteLine("I am a GrandFather");
    }
}

public class Father: GrandFather
{
    public override void WhoAreYou()
    {
        Console.WriteLine("I am a Father");
    }
}

public class Child : Father 
{
    public override void WhoAreYou()
    {
        Console.WriteLine("I am a Child");

    }
}

I want to print "I Am a grandfather" from the "child" object.

How could i do the Child object execute a Method on a "base.base" class? I know i can do it executes the Base Method (it would Print " I Am a Father"), but i want to print "I Am a GrandFather"! if there is a way to do this, Is it recommended in OOP Design?

Note: I do not use / will use this method, I'm just wanting to intensify knowledge inheritance.


Solution

  • This can only be possible using Method Hiding -

    public class GrandFather
    {
        public virtual void WhoAreYou()
        {
            Console.WriteLine("I am a GrandFather");
        }
    }
    
    public class Father : GrandFather
    {
        public new void WhoAreYou()
        {
            Console.WriteLine("I am a Father");
        }
    }
    
    public class Child : Father
    {
        public new void WhoAreYou()
        {
            Console.WriteLine("I am a Child");            
        }
    }
    

    And call it like this -

    Child child = new Child();
    ((GrandFather)child).WhoAreYou();
    

    Using new keyword hides the inherited member of base class in derived class.