When does the Constructor gets called in java?

前端 未结 10 1365
[愿得一人]
[愿得一人] 2020-12-16 02:14

When does the Constructor get called?

  1. Before object creation.
  2. During object creation.
  3. After object creation.
10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 03:08

    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

    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

提交回复
热议问题