Tech News

Can an abstract class have a constructor ?

Yes, an abstract class can have a constructor. 

In general, a class constructor is used to initialize fields. Along the same lines, an abstract class constructor is used to initialize fields of the abstract class.

An abstract class constructor can also be used to execute code that is relevant for every child class. This prevents duplicate code.

You can not create an instance of an abstract class, so what is the use of a constructor in an abstract class?

You can not create an instance of the abstract class, we can create instances of the classes that are derived from the abstract class.

So, when an instance of the derived class is created, the parent abstract class constructor is automatically called.

Note: Abstract class cant be directly instantiated, The abstract class constructors get executed thru a derived class. So, it is a good practice to use a protected modifier with an abstract class constructor,using public doesn’t make sense.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x