Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do abstract classes in Java have constructors? [duplicate]

Why does an abstract class in Java have a constructor?

What is it constructing, as we can't instantiate an abstract class?

Any thoughts?

like image 480
gameover Avatar asked Jan 31 '10 03:01

gameover


People also ask

Why do abstract classes have constructors in Java?

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.

Why do classes have multiple constructors Java?

A class can have multiple constructors, as long as their signature (the parameters they take) are not the same. You can define as many constructors as you need. When a Java class contains multiple constructors, we say that the constructor is overloaded (comes in multiple versions).

Why abstract class has constructor even though you Cannot create object?

Because it's abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it. abstract class has a protected constructor (by default) allowing derived types to initialize it.

Can abstract class have constructors in Java?

Like any other classes in Java, abstract classes can have constructors even when they are only called from their concrete subclasses.


2 Answers

A constructor in Java doesn't actually "build" the object, it is used to initialize fields.

Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.

Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.

like image 115
Uri Avatar answered Oct 16 '22 01:10

Uri


Two reasons for this:

1) Abstract classes have constructors and those constructors are always invoked when a concrete subclass is instantiated. We know that when we are going to instantiate a class, we always use constructor of that class. Now every constructor invokes the constructor of its super class with an implicit call to super().

2) We know constructor are also used to initialize fields of a class. We also know that abstract classes may contain fields and sometimes they need to be initialized somehow by using constructor.

like image 35
Debmalya Avatar answered Oct 16 '22 02:10

Debmalya