Pages

Sunday, February 5, 2017

Class Loading and Object


Example:

class Hello 
{
    int a = 99;
    static int b = 88;
    
    Hello(){
        System.out.println("Hello D.C");
    }

    {
        System.out.println("Hello I.B");
    }

    static{
        System.out.println("Hello S.B");
    }

    public static void main(String[] args) 
    {
        Hello h = new Hello();
    }
}

Here is what happens when the above class is compiled and run

  1. Allocates 8 bytes of memory for the reference variable (h) and initializes with null value.
  2. Verifies whether the class is loaded or not.
  3. If not loaded, then loads the class by doing the following tasks:
    1. Reads the byte code from .class file and loads into main memory.
    2. Allocates memory for static variables and initializes with default or specified values.
    3. Executes static blocks.
  4. Constructors will be invoked. Statement of the constructor will not be executed.
  5. Allocates the memory for instance variables of the class and initializes with default or specified values.
  6. Instance block will be executed.
  7. Statements from the constructor will be executed.
  8. Address of newly created object will be assigned to the reference variable.

No comments:

Post a Comment