Home > other >  can we create an object of class inside instance block?
can we create an object of class inside instance block?

Time:12-27

class ObjectCreation {
    {
        ObjectCreation obj = new ObjectCreation();
        System.out.println("I am Instance Block Object "   obj.hashCode());
    }     

    public static void main(String[] args) {
        ObjectCreation obj = new ObjectCreation();
        System.out.println("I am main method Object "   obj.hashCode());
    }
}

.java:5) at ObjectCreation.(ObjectCreation.java:5)

I found this runtime exception on console. Why we are not able to create object of same class? in instance block

CodePudding user response:

Because it would lead to an infinite loop.

So in your main code you want to create a new instance of ObjectCreation, like so :

 ObjectCreation Obj = new ObjectCreation();

So the JVM has to initialise that new object, which means it will call the instance block for it - which does a

ObjectCreation Obj = new ObjectCreation();

So the JVM has to initialise that new object, which means it will call the instance block for it - which …

well, you get the idea !

CodePudding user response:

Initializer blocks are used to initialize instance variables. Post compilation, Java compiler copies initializer blocks into every constructor. Read more about initializer block here.

  •  Tags:  
  • java
  • Related