Reputation: 2025
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?
Upvotes: 6
Views: 8162
Reputation: 9
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
}
Upvotes: 0
Reputation: 2288
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 :
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
Upvotes: 0
Reputation: 5176
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.
Upvotes: 2
Reputation: 393841
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.
Upvotes: 7