Below code:
public class Program
{
static void Main(string[] args)
{
father f = new son(); Console.WriteLine(f.GetType());
f.show();
}
}
public class father
{
virtual public void show()
{
Console.WriteLine("father");
}
}
public class son : father
{
public override void show()
{
Console.WriteLine("son");
}
}
The result is ‘son’.
If I modify the ‘public override void show()‘ to ‘public new void show()‘,the result is ‘father’.
So I conclude below ‘rules’:
- Use ‘override’, which function will be called is determined in run
time. The program will choose the right function according to the
real type of current object.(As above, the f’s runtime type is son,
so it calls the son’s show.) - Use ‘new’ modifier, which function will be called is determined when
it is compiled.The program will choose the object’s declared type to
call its function.(As above, the f’s declared type is father ,so
using ‘new’ modifier make the output to show ‘father’.
All above are what I understand about polymorphism.Any misunderstanding and wrong?
Not really. The decision is still made at execution time, but the
newmethod does not override the virtual method in the base class. This is most easily shown by extending your example somewhat:Here, at compile time the decision is made to call the most overridden implementation of
Base.Foo– if there were multipleFoosignatures, the decision about which signature to use would be taken, for example. Which implementation will be “the most overridden” is unknown at this point, of course.At execution time, the CLR will find that most overridden implementation based on the actual type of the target object – which is
MoreDerived. ButMoreDerived.Foodoesn’t overrideBase.Foo… whereasDerived.Foodoes, so the implementation inDerivedis the one which is actually executed.