public class A
{
public virtual void Write() { Console.Write("A"); }
}
public class B : A
{
public override void Write() { Console.Write("B"); }
}
public class C : B
{
new public virtual void Write() { Console.Write("C"); }
}
public class D : C
{
public override void Write() { Console.Write("D"); }
}
// ...
D d = new D();
C c = d;
B b = c;
A a = b;
d.Write();
c.Write();
b.Write();
a.Write();
Why doesn’t D Write() override B Write() if the actual object that b is referencing is D?
Mike Lol is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
The reason is that in C
you have:
new public virtual void Write() { ... }
Which means it no longer overrides B.Write()
(which overrides A.Write()
.
Then D.Write()
overrides the Write
method in its direct base class – C
.
If you change the method in C
to be:
public override void Write() { ... }
All the classes in your hirachy will override the same method in A
and you will get the output you expect (DDDD
).