Four Basics of Object-Oriented Programming(OOPS)
As in my last article we learnt that OOPs help us to write DRY code i.e. writing reusable code to make programmers life easier. Now we'll learn what are main part of OPPs or basics of OOPs :
The four pillars for OOP are Abstraction, Encapsulation, Inheritance and Polymorphism. Let's take one-by-one to these all:
Abstraction
Abstraction is the process of showing only essential/necessary
features of an entity/object
to the outside world and hide the other irrelevant information.
For example to open your TV we only have a power button, It is not required to understand how infra-red waves are getting generated in TV remote control.
An abstract class is a special type of class that cannot be instantiated and acts
as a base class for other classes.
The purpose of an abstract class is to provide a common
definition of the base class that multiple derived classes can share and can be used only
as a base class and never want to create the object of this class
Some programmer may ask a question that if it need to hide some features of any class from out side the world then make that particular method
private
! Isn't it? Absolutely not!!
abstract class DNP_Demo() { private abstract void CallThis(); }
If we use the private
access specifier for an abstract method then it will throw an error,
because if we declare an abstract
method as private then the derived classes cannot override it and that is inconsistent with the rules of abstract classes.
So we cannot use have a private
access specifier for an abstract method.
The access modifier of the abstract
method should be the same in both the abstract class and its derived class.
If you declare an abstract
method as protected
,
it should be protected
in its derived class. Otherwise, the compiler will raise an error.
Constructor inside Abstract Class?
Well, now again next question come in mind that if we do not create object of abstract class then can we have Constructor
inside abstract class? We know
that abstract class will always be base class and when any child class will be called then as per object creation hierarchy first of all
base class contructor would be called. So it must be Constructor inside Abstract Class
.
Few more intresting points about Abstract Class
Why Abstract Class?
Summary
To summarise, if we want to provide some method to a base class that must be implemented in a derived class then we can use an abstract class
and make the method abstract.
Hope you picked up a thing or two.
Cheers!