Constructor in Abstract | Core Java Forum
D
Deepak Posted on 28/01/2019

What is the use of having constructor in Abstract class, when object cannot be created for abstract class?


Y
Yogesh Chawla Replied on 28/01/2019


Let's recall the definitions first;

A constructor is created to make sure all non static data members are initialized at the time of the object creation itself so
objects can further invoke methods containing business functionalities with those same non static data members.

And abstract class is defined mainly to declare unique functionality for child classes to define and common functionality for child classes to use
so no unnecessary redundant piece of code is written again and again within project.

Now see this example:

abstract class Product {
int multiplyBy;

// Constructor in abstract class
Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}

// Common Functionality
int multiply(int val) {
return multiplyBy * val;
}
}

Here superclass Product is abstract and has a constructor. Now Let's see two child concrete child classes,

first is

class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}

This concrete child class TimesTwo has a constructor where in we are just calling constructor of parent abstract class with value 2 so
with the help of constructor in abstract class we can use the common functionality also which is multiply method.

Note:
There is no default (or no-arg) constructor in the parent abstract class so the constructor used in subclasses have to explicitly call
the parent abstract class constructor so this whole functionality will make much more sense and it's also coded in the right way also.

Basically we have tried to make maximum use of Abstract Class Functionality.

Now Let's see second concrete child class

class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}

This second concrete child class TimesWhat has a constructor that allows the caller to specify the value. Just another scenario.

Basically Abstract class constructors are frequently used to enforce class constraints or invariants such as the minimum fields required to setup the class.

In nutshell, yes constructors and static methods are all allowed to be written as part of abstract class and at the same
time, abstract class objects CAN ALSO NEVER BE INITANTIATED because these concepts(constructors and static methods within abstract classes) are
basically written for child classes only and abstract class in general is also written for child classes to use. This is the reason why we can have
constructors written as part of abstract classes without abstract class object not being able to instantiate itself.


D
Deepak Replied on 29/01/2019

Thanks alot sir..it was very clear.