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");
}
}
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.
The problem is C
not overriding a function from a class A
. The compiler gives you a keyword warning new
. If you also use override
in a class C
, it works as you'd expect.
Or, if you replace A obj = new D();
with D obj = new D();
, you get the same result.