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 does it mean that even if a constructor completes running without any exception, there is no guarantee whether an object is created?
When we create a Subclass object which extends an abstract class, the abstract class
Share
Simply speaking, a
constructordoes not create an object. It just initializes the state of the object. It’s thenewoperator which creates the object. Now, let’s understand this in little detail.When you create an object using statement like this:
The object is first created by the
newoperator. Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object.Now consider the case of
Abstract classand it’s concreteSubClass, when you do like this:newoperator creates an object ofConcreteClass, and invokes its constructor to initialize the state of the created object. In this process, the constructor of the abstract class is also called from theConcreteClassconstructor, to initialize the state of the object in the abstract class.So, basically the object of
AbstractClassis not created. It’s just that it’s constructor is invoked to initialize the state of the object.Lessons Learnt:
The object is created by
newoperator, and not by the invocation of the constructor itself. So, the object is already created before any constructor is invoked.Constructor is just used to initialize the state of the object created. It does not create an object itself.
An object state can also be contained in an abstract super class.
Abstract classconstructor, is only to initialize the object completely, and no object is created in process.See: