I have three classes.
Person -> Employee -> Manager
Person has a virtual method declared as
public virtual void saySomething()
Inside of Employee I have
public virtual void saySomething()
OR
public override void saySomething()
And I get the same behavior
Inside of Manager I have
public override void saySomething()
I'm confused with the fact that I can use override in replace of virtual? I thought you use override to signify the开发者_开发知识库 fact that this class has overridden one of the base class function.
How do I stop a method from being overriden? This is the last method.
Adding public virtual void saySomething()
in the subclass is re-declaring the method (method-hiding; you probably get a warning about that).
It will behave the same if you access it as:
Employee emp = ...
emp.saySomething();
but now add:
Person per = emp;
per.saySomething();
With polymorphism (via override
) they should do the same thing. But via method-hiding they won't. To explicitly hide a method, use new
:
new public virtual void saySomething() {...}
or to stop something being overridden any further, use sealed
:
public sealed override void saySomething() {...}
You can use the sealed
keyword to stop a virtual being overridden any further in your inheritance hierarchy.
Your use of override is correct in Employee
, you want to override the default implementation provided by Person
. virtual
in the Employee
type for the saySomething
method is incorrect.
You have to use sealed key word.
精彩评论