An Example of Using a static Initializer in a Class - Java Object Oriented Design

Java examples for Object Oriented Design:Static

Description

An Example of Using a static Initializer in a Class

Demo Code

public class Main {
  private static int num;
  
  // A static initializer. Note the use of the keyword static below.
  static {/*from   www .ja  v  a  2  s .  co m*/
    num = 1;
    System.out.println("Inside static initializer.");
  }

  // An instance initializer
  {   
    System.out.println("Inside instance initializer.");
  }

  // Constructor
  public Main() {
    System.out.println("Inside constructor.");
  }

  public static void main(String[] args) {
    System.out.println("Inside main() #1. num: " + num);

    // Declare a reference variable of the class
    Main si; 

    System.out.println("Inside main() #2. num: " + num);

    // Create an object
    new Main();

    System.out.println("Inside main() #3. num: " + num);

    // Create another object
    new Main();
  }
}

Result


Related Tutorials