Does invoking a constructor mean creating object?

Hence does it mean that even if a constructor completes running
without any exception, there is no guarantee whether an object is
created?

Simply speaking, a constructor does not create an object. It just initializes the state of the object. It’s the new operator which creates the object. Now, let’s understand this in little detail.

When you create an object using statement like this:

new MyClass();

The object is first created by the new operator. 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 class and it’s concrete SubClass, when you do like this:

AbstractClass obj = new ConcreteClass();

new operator creates an object of ConcreteClass, 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 the ConcreteClass constructor, to initialize the state of the object in the abstract class.

So, basically the object of AbstractClass is 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 new operator, 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.

  • So, the purpose of invocation of Abstract class constructor, is only to initialize the object completely, and no object is created in process.

See:

Leave a Comment