简体   繁体   中英

Why can't we have abstract constructor in 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?

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.

You can't have an abstract constructor, as abstract means you need to provide the implementation for that at some point of time in your subclass. But you cannot override constructor. There will be no point in having an abstract constructor :

  1. Since the constructor needs to be of the same name as of class.
  2. You will always call the constructor of child class and not of base class

Abstract constructor will have no meaning, since constructor is directly related to object creation of a particular type. Also there is no way by which we can define a constructor for any other class from a given class.

But if you still want to enforce this kind of pattern, you need to go with the abstract factory pattern

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.

When you set a constructor as 'abstract', you are essentially saying:

This constructor doesn't have a body and you want to implement it at another time in a child class

However, the constructor is called implicitly when an Object is created, so we can't implement the constructor that's why constructors are not abstract.

abstract class BaseClass {
  abstract BaseClass() // compile time error
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM