The following example illustrates the
override keyword:
public class BaseClass { public virtual void AMethod() { } } public class DerivedClass : BaseClass { public override void AMethod() { } } // ... BaseClass baseClass = new DerivedClass(); baseClass.AMethod();
In the preceding example,
DerivedClass.AMethod will be called; because, it overrides BaseClass.AMethod.If the
new keyword were used instead of the override keyword, then the method in the derived class would not override the base class method, but would hide it instead. The following is an example illustrating the new keyword:public class BaseClass { public virtual void AMethod() { } } public class DerivedClass : BaseClass { public new void AMethod() { } } // ... BaseClass baseClass = new DerivedClass(); baseClass.AMethod(); DerivedClass derivedClass = new DerivedClass(); derivedClass.AMethod();
The preceding example will call
BaseClass.AMethod first, followed by DerivedClass.AMethod. Effectively, the two methods are unrelated except for the fact that they have the same name.If neither the
new nor overrides keyword is specified, the result is the same as if the new
were specified. However, a compiler warning will be generated to ensure
that the programmer is aware that a method in the base class is being
hidden.
No comments :
Post a Comment