Why does an abstract
class in Java have a constructor
?
What is it constructing, as we can't instantiate an abstract
class?
Any thoughts?
This question is related to
java
constructor
abstract-class
Implementation wise you will often see inside super() statement in subclasses constructors, something like:
public class A extends AbstractB{
public A(...){
super(String constructorArgForB, ...);
...
}
}
Because another class could extend it, and the child class needs to invoke a superclass constructor.
I guess root of this question is that people believe that a call to a constructor creates the object. That is not the case. Java nowhere claims that a constructor call creates an object. It just does what we want constructor to do, like initialising some fields..that's all. So an abstract class's constructor being called doesn't mean that its object is created.
All the classes including the abstract classes can have constructors.Abstract class constructors will be called when its concrete subclass will be instantiated
Because abstract classes have state (fields) and somethimes they need to be initialized somehow.
Two reasons for this:
1) Abstract classes have constructors
and those constructors are always invoked when a concrete subclass is instantiated. We know that when we are going to instantiate a class, we always use constructor of that class. Now every constructor invokes the constructor of its super class with an implicit call to super()
.
2) We know constructor are also used to initialize fields of a class. We also know that abstract classes may contain fields and sometimes they need to be initialized somehow by using constructor.
Source: Stackoverflow.com