Friday, March 25, 2022

Instance Blocks

  • Instance blocks can be used to initialize variables or to execute any logic during object creation.
  • Whenever an object is created, instance blocks will be executed
  • Instance blocks will be executed before constructor
  • If there are multiple instance blocks then those will be executed from top to bottom.
  • A class can have any number of instance blocks, and they can appear anywhere in the class body.
public class Main {
    private int number = 200;
    {
        System.out.println("inside instance block");
        this.number = 300;
    }
    public Main(int number) {
        System.out.println("inside constructor");
        this.number = number;
    }
    public static void main(String[] args) {
        var mainObj = new Main(100);
        System.out.println(mainObj.number);
    }
}

//output
inside instance block
inside constructor 
100 

No comments:

Post a Comment