Today in this section, we will extend Polymorphism by looking at abstract classes.
Abstract classes are concept wherein you will never make an instance of base class but derived class. Hence, when you make an abstract class, you also create abstract methods which must be overridden in derived class. Therefore, in a nutshell, Abstract class does the following things:-
- Abstract classes can’t be instantiated
- Must Derive from Abstract class
- Abstract methods created must get overridden in derived classes.
- Abstract class can also have non abstract methods with implementation
- Purpose of abstract classes is clear. It has to create a contract which all the derived classes will implement.
Let us go ahead and see the demo around. Below, I have created simple Abstract class with abstract and non abstract methods to it. I have also used default and Parameterized constructor to set the values in there.
Below, I have created new class and simply implemented the same using VS. And, as a result, here is the default implementation for the same.
Now, let me go ahead and add few properties to it as well. While doing so, you can observe that base properties coming from abstract class.
Here is the finished class.
Now, let us go ahead and create object for the same in the main class.
With the above change in place, when I go ahead and run the same, it will produce the following output.
Below stuff is also very much legal. Although, we are having variable of type abstract class but we are creating an instance of derived class.
With this, It will produce similar output as shown below.
However, Below shown scenario is not legal obviously.
With this, I would like to wrap up this session. Thanks for Joining Me.
Download Code :- https://github.com/rahulsahay19/AbstractClass
1,830 total views, no views today