Reputation: 874
"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.
Upvotes: 1
Views: 1169
Reputation: 1
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 .
Upvotes: 0
Reputation: 81243
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
.
Upvotes: 5
Reputation: 1570
Try to use the "new" keyword instead of "override" and remove the "virtual" keyword from methods;)
Upvotes: 2