Abstract confusion of class inheritance
I have class D inheriting from abstract class C and writing to a console related message. I expect to see "D" in the console window, but it writes "B". I think the virtual keyword in class C is breaking the rule. I didn't understand why. Can someone please explain?
class Program
{
static void Main(string[] args)
{
A obj = new D();
obj.Write();
Console.Read();
}
}
public abstract class A
{
public virtual void Write()
{
Console.WriteLine("A");
}
}
public abstract class B : A
{
public override void Write()
{
Console.WriteLine("B");
}
}
public abstract class C : B
{
public virtual void Write()
{
Console.WriteLine("C");
}
}
public class D : C
{
public override void Write()
{
Console.WriteLine("D");
}
}
+3
source to share
2 answers
Your compiler already works pretty well here if you listen to it:
warning CS0114:
'C.Write()' hides inherited member 'B.Write()'.
To have the current member override this implementation, add the override keyword .
If not, add a new keyword .
The fact that you used virtual
instead override
in C will result new
in the default behavior for that method, breaking the inheritance chain.
+2
source to share