As i have studied that constructors are used to create class objects and initialize instance fields.But in abstract class the constructor is also created when the subclass inherits abstract class and we create an object of subclass.According to abstract class definition we can't create an object of abstract class.So how it is possible to call a constructor of an abstract class without creating an object of it.
-
1A constructor doesn't instantiate a class, it initializes the instance fields. – Sotirios Delimanolis Mar 05 '14 at 06:51
-
possible duplicate of [Can an abstract class have a constructor?](http://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor) – eatSleepCode Mar 05 '14 at 07:05
5 Answers
When you create a subclass, you are forced to call a super class constructor.

- 4,777
- 1
- 21
- 44
I'm not sure how well this answers your question, but in my experience I've only used abstract constructors to call a super()
in the subclass constructors. I can't say Parent x = new Parent();
but I can say Parent y = new Child()
where the first line of Child()
is super();
, essentially calling Parent();
.

- 893
- 1
- 7
- 15
We can not create the object of abstract class but we can create the constructor of abstract class and we can call it in sub class using super()
abstract class abc{
abc(){}
}
class Test extends abc{
super();
}
A contructor intialize the instance of the fields and give them default values if they dont have any value at the time of intialization
class A{
int b;
}
A a = new A();
System.out.println("value of b "+b);
answer is : value of b 0
the constructor intialize the fileds with default values

- 1,436
- 3
- 18
- 33
By using super()
you can call constructor of abstract class from its sub class.
For eg. your abstract class
have fields a
and b
and you want to initialize those so this can be done from its sub class
by using abstract class
constructor
and super()
.

- 4,427
- 7
- 44
- 93
I think the best answer is in the first comment. You don't actually use the constructor in this case to instantiate the abstract class but to initialize its state and the invariants. Let's say you were allowed to create a subclass without calling super(...), there would be cases where you'd have a partially constructed object
public abstract class AbstractMe {
protected List<Object> objects;
protected AbstractMe() {
objects = new ArrayList<>();
}
protected int elements() { return objects.size(); }
}
If you call super elements will always work fine, but if you were allowed not to call it it could be a NPE even if your invariant is that there always is a list in your class.

- 1,113
- 5
- 12