Abstract class or Interface : the most confusing decision in the programming world when to go with which. Let us understand each one in detail and try to answer this question.
OK so let’s discuss about them one by one.
An abstract class, just like any other class is a collection of fields, properties and methods. It has got behavior of its own. The only difference is that an abstract class cannot be instantiated; and of course the use of the keyword “abstract” in the class declaration.
It can have methods that contain a method body or even ones that contain only declaration (abstract methods).
Now, coming over to some points we all get confused about. The “Myths and Truths” of the abstract class –
Myth : Abstract class must contain at least one abstract method.
Truth : Abstract classes need not have any abstract methods. But a class containing even one abstract method must be declared abstract.
Now the question arises what is the use of such a class? Such an abstract class would just prevent a user from instantiating the given abstract class, while providing a default implementation for all child classes.
Myth : Abstract class cannot be instantiated and hence cannot contain a constructor..
Truth : Abstract classes cannot be instantiated yet it can contain a constructor.
Once again, the question arises what is the use of having constructor if it cannot be instantiated?
This is so because abstract classes are based upon the concept of inheritance and in C#, whenever an object of a derived class is instantiated, prior to calling the constructor of the child class, the constructor of super-class is called and this is where a constructor of abstract class comes in use.
So this was all about abstract classes. We would be discussing interfaces, their differences and which to use when in the following posts………..