When we create a Subclass object which extends an abstract class, the abstract class constructor also runs . But we know we cannot create objects of an abstract class. Hence
When you invoke a constructor using new
, a new object is being created.
Now, as you probably already know, every constructor of any subclass, either implicitly or explicitly, directly or indirectly, invokes a constructor from the parent class (which, in turns, invokes one from its own parent class, all the way up to object). This is called constructor chaining.
The above, however doesn't mean that multiple objects are created. The object has been created at the new
call and all constructors working on that object are already handed an allocated area. Therefore, constructor chaining does not create new objects. One call to new
will return you one object.
But we know we cannot create objects of an Abstract class
Right but JVM can.
does it mean that even if a constructor completes running without any exception , there is no guarantee whether an object is created ?
The object is definitely created internally.
Does invoking a constructor mean creating object?
Not always. you can invoke constructor using super()
and this()
but it won't instantiate an object. (but will just invoke the constructor)
class AClass
{
AClass()
{
this(1); // will invoke constructor, but no object instatiated.
}
AClass(int a)
{
}
public static void main(String[] args)
{
AClass obj = new AClass(); // one object instantiated.
}
}