An Idea can change your life.....

Monday, April 07, 2008

The Semantics of override

Declaring a method as "sealed" means that you ARE NOT ALLOWED to override that method. It is enforced by the compiler.

Calling a method of a derived class through its base class is polymorphism, . The new keyword creates a method that will not be callable through a method of the base class(es).

So, the purpose of the sealed keyword? It prevents inheriting classes to override the method. And let me perfectly clear: overriding a method in a derived class is not the same as declaring a method with same name and the new modifier (or without the override modifier) in a derived class.

Public class A
public virtual void MethodX() {}
public virtual void MethodY() {}

public class B : A
public override void MethodX() {}
public override sealed void MethodY() {}

public class C : B
public override void MethodX() {}
// public override void MethodY() {} // NOT ALLOWED, COMPILER ERROR
public new void MethodY() {}


A varA = new C();
A varB = new B();
C varC = new C();

varA.MethodX(); // Calls C.MethodX()
varA.MethodY(); // Calls B.MethodY() because MethodY is not overriden in class C
varB.MethodX(); // Calls B.MethodX()
varB.MethodY(); // Calls B.MethodY()
varC.MethodX(); // Calls C.MethodX()
varC.MethodY(); // Calls C.MethodY()

So the only way to call C.MethodY() is by explicitly creating a variable of type C. MethodY of class C is not a virtual

No comments: