Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors in abstract classes? [duplicate]

Tags:

Why can an abstract class have a constructor? As we can't create an object of it why would we need a constructor in an abstract class?

like image 813
developer Avatar asked Mar 23 '11 10:03

developer


People also ask

Does an abstract class have a copy constructor?

Yes you should. Rules of having your own implementations for copy constructor, copy assignment operator and destructor for a Class will apply to even an Abstract Class.

Should Abstract classes have constructors?

The main purpose of the constructor is to initialize the newly created object. In abstract class, we have an instance variable, abstract methods, and non-abstract methods. We need to initialize the non-abstract methods and instance variables, therefore abstract classes have a constructor.

Can we define constructor in abstract class?

Yes, we can define a parameterized constructor in an abstract class.

Are abstract constructors inherited?

These members include a constructor, because constructors aren't inherited.


1 Answers

In some cases we need to initialize the fields in the abstract class. If it is a empty constructor this is done implicit by the constructor in the child class, otherwise we use super(parameters). A constructor with parameters forces the child class to specify some parameters (not necessarily from its own parameters).

All in all, this means that the constructor is used by the child class constructor and not from the "outside".

like image 193
Lasse Espeholt Avatar answered Oct 10 '22 16:10

Lasse Espeholt