Illustration of Abstract Classes of C# (C Sharp) with ExamplesIn your C#
code, you might have used inheritance. Did you ever get a situation where
in you have to define a class which can only take part in inheritance
and it cannot be instantiated. If so, how can you accomplish it? You can
accomplish it using abstract classes. This article will help you in understanding
abstract classes and abstract methods.
Abstract Classes: General characteristics and restrictions of abstract classes are mentioned below: A
class becomes an abstract class if you include the keyword abstract in
the class declaration Here is a simple example for abstract class: abstract
class car { Output of
the code will be: If you included
the following line of code inside Main method, Then you will end up in error since abstract classes cannot be instantiated. Abstract Methods in Abstract Class: In the above example, your abstract class included a virtual method called displayMsg. Virtual means that the method has to be overridden. However it doesnt force you to override. Hence in the above example, none of the derived classes have overridden this method. It is legal and all methods are allowed to access it. In the Main method of testClass, you created an instance of alto class and called the displayMsg. This executes the base class method. In the above example, you will get the same output You are dealing with a Car for all cars. What if your user doesnt agree with it and he wants specialized message for each car. Then you can modify the code as shown below: abstract
class car { Output of this code will be: You are dealing
with Indica Car You have got the desired output. But still there is a problem with this code. Virtual methods may or may not be overridden in derived class. Since you know that User requires specialized output, you have overridden it. What if at a later point of time, a new car called swift gets introduced and it is implemented by a different developer, then the developer might code it as: class swift
: car { } Output
of this code will be: This is again undesirable by the User. So the best way to avoid this situation is to force developers to override the method displayMsg. This can be done by associating the keyword abstract with displayMsg instead of virtual. Assume that you have changed the car class as shown below: abstract
class car { Then you must override this method in all its derived classes. If not, then it will end up in error. To summarize on abstract methods, here are its basic characteristics and guidelines: Abstract
classes may or may not define abstract methods
|