Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we have abstract constructor in java?

Tags:

java

I was wondering what was the design considerations in java that prevented classes like this?

public abstract class A{
    public abstract A();
}

If we could force implementation of constructors,then we could instantiate abstract classes. But why didn't they? Does this violate OOP design or is it simply not possible?

like image 555
armin Avatar asked Mar 03 '15 06:03

armin


People also ask

Why constructor is not abstract in Java?

Java constructor can not be abstract If we are declaring a constructor as abstract as we have to implement it in a child class, but we know a constructor is called implicitly when the new keyword is used so it can't lack a body and also it can not be called as a normal method.

Can we have constructor in abstract?

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

Why we can create constructor in abstract class but we Cannot initialize it?

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.


2 Answers

An abstract constructor would have no meaning.

An abstract method forces all concrete sub-classes to implement a method of the same signature (which includes the same name).

However, a concrete sub-class can't implement a constructor having the same name as the "abstract constructor" of the abstract class, since a constructor must have the name of the class in which it appears.

like image 83
Eran Avatar answered Oct 31 '22 05:10

Eran


An abstract modifier is meant for those whose implementation is yet to be given.

Considering a situation (like the one you just asked) the constructor itself is abstract so its class creation cannot actually happen.

Why

For a class to exist its default constructor will be invoked by the the system automatically. But now as you have provided your own constructor (which additionally is abstract), the default one won't exist and hence this class won't exist.

Hence an inconsistent situation to be in.

Hope it helps.

like image 28
cafebabe1991 Avatar answered Oct 31 '22 04:10

cafebabe1991