1

"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.

Marcel James
  • 834
  • 11
  • 20

3 Answers3

5

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.

Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
2

Try to use the "new" keyword instead of "override" and remove the "virtual" keyword from methods;)

Vajda Endre
  • 1,512
  • 1
  • 16
  • 26
0

This program gives error when u run. Make sure the object of child will refer parent class then use reference type casting calling method Ex: child child = new grandfather();/here we are creating instance of child that refer parentclass./ ((Grandfather)child).WhoAreYou();/* now we able to use reference type*/ Otherwise they show error under grandfather type casting .