The “override” keyword is used to hide the definition of a method in the derived class. Whereas the new keyword is used to provide a new definition for the method.
The "virtual “ keyword make the method to be overridden in the derived class.
Let us understand the difference like this. When we declare a parent object and instantiate it with the child object, and when we use this object to call overridden method then the child class method will be executed. And in case of new method the parent class method will be called.
So in case of overriding , this is called as polymorphism.
But if we have declared child object and instantiating it with the same, and then if we make a call to the method with the object then in both the cases the derived method will be invoked. Lets see this with an example.
Here we have one base class named “Base”, which has two member methods, “one()” that is marked as virtual. Other is “two()” which is a non-virtual method.
Now we have a class “Child” which is derived from the “Base”. It has overriden method “one()” and a new method “two()”.
In the Main() method we have declared “b” as Base type and instantiated it with the Child type. And “c” is declared and instantiated as “Child” type.
When one execute this piece of code, following will be the observation:
Child overridden method one
Child new method two
Child overridden method one
Base non virtual method TWO
Thus it can be seen, our point is very clearly demonstrated with this example.
July 10, 2009
Virtual, Override, New keywords in .net
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment