Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the Constructor gets called in java?

Tags:

java

When does the Constructor get called?

  1. Before object creation.
  2. During object creation.
  3. After object creation.
like image 226
Sushant Avatar asked Mar 05 '12 13:03

Sushant


People also ask

When can constructor get called?

The constructor gets called when a new object is created.

When the constructor will get executed in Java?

The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.

When constructor method is called?

It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

How are constructors called in Java?

Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.


2 Answers

The object memory is allocated, the field variables with initial values are initialized, and then the constructor is called, but its code is executed after the constructor code of the object super class.

like image 128
Luciano Avatar answered Sep 19 '22 08:09

Luciano


After the Object creation

once an object is created using new operator like Student s = new Student(); first Student object is created, and then constructor is called to initialize the variable of the object

We can prove constructor is called after creating the object by using below code

code to prove constructor is called after object creation

enter image description here

here we are using instance block. And also instance block is executed before the constructor

so I am printing hash code in three places

  1. Inside Instance block
  2. Inside Constructor
  3. Inside main mehtod

all these three times hash code is equal, that means object is created before the constructor is executed

because having a hash code means, there must be an object. And if hash code printed inside both instance block and constructor is equal. that means object must be created before the constructor execution

like image 24
Masith Prasanga Avatar answered Sep 21 '22 08:09

Masith Prasanga