Sunday, January 4, 2009

Difference between virtual and abstract - Similar working nature but having different reason to be there

Well, Virtual methods allow subclasses to provide their own implementation of that method using the override keyword if they are wished while Abstract methods in a class contain no method body, and are implicitly virtual.Neither abstract or virtual can be declared private, since it will crush the purpose, and subclasses must override them using the same method signature.If a class has any abstact methods, then it must report itself as abstract I mean it has to, so that no instances of it can be created.
If a subclass needs to override a member (i.e. you can't specify a meaningful body in the base class, as it can't be defined), then it should be declared abstract and it will act as base-class. But if you just want to give the subclass the ability to override a method then it should be virtual.Any abstract member forces the entire class to be abstract, it means you can't create actual instances of the base class.
You must override when you deriving from abstract class. You can override methods (if for some reason you need to do something else) when you deriving from virtual.
In some cases you cannot provide an implementation for some methods, but method has to be there because it is part of the class interface. You want the programmers using the class to provide this implementation and you don't want to let them instantiate objects of this class because without this method it won't simply work. In this case you declare the method and the class as abstract. Abstract classes cannot be instantiated because they are not complete.
In other cases you can provide a default implementation of a method which is fair enough to make the control work even if not re-defined or changed, but you want to give the programmers using your class as a base class to provide their better implementation. In this case you declare the method as virtual thus, giving the programmers options whether to use the default or provide their own implementation and twist the results.
-
*Sharp Electronics PW-E550 Electronic Dictionary

No comments:

Post a Comment