Reputation: 11
If I have a class named "Parent"
for example. he has a method named "Print".
the class "Kid"
is derived, it has a method named "Print"
, but a new one.
new public void Print;
Let's create an object:
Parent p = new Kid();
If I'll use the method Print with this object's pointer the method will be the father's("Parent") method, not the "Kid".
But when I'm using a virtual method, the method will be the Kid's not the parent.(if the Print was virtual, the print in the "Kid" overrides the method")
Why?
Upvotes: 0
Views: 388
Reputation: 700152
A virtual method call uses the actual type of the object to determine which method to call, while a non-virtual method uses the type of the reference.
Say that you have:
public class Parent {
public void NonVirtualPrint() {}
public virtual void VirtualPrint() {}
}
public class Kid : Parent {
public new void NonVirtualPrint() {}
override public void VirtualPrint() {}
}
Then:
Parent p = new Parent();
Parent x = new Kid();
Kid k = new Kid();
p.NonVirtualPrint(); // calls the method in Parent
p.VirtualPrint(); // calls the method in Parent
x.NonVirtualPrint(); // calls the method in Parent
x.VirtualPrint(); // calls the method in Kid
k.NonVirtualPrint(); // calls the method in Kid
k.VirtualPrint(); // calls the method in Kid
Upvotes: 0
Reputation: 10840
When you use the new keyword with a method having same signature as that of a method in parent, it shadows the parent method. Shadowing is different from overriding. Shadowing means your new method will be called if both instance and variable are of type child. Whereas overriding ensures that your overriden method will be called no matter variable is of type child or parent.
Edit:
Take a look at the comparison sheet on MSDN.
Upvotes: 1