Thursday, August 11, 2016

Class and Object: Order of execution

// a class can have various modifiers (public, private, final, static, abstract)
// not all are available in all cases
public final class OrderOfExecution {

    static {
        System.out.println("static initializer");
        // Executed when the class gets loaded
    }

    {
        System.out.println("initializer");
        // Executed when an instance gets created,
        // before the constructor
    }

    public OrderOfExecution() {
        System.out.println("constructor");
    }

    public void doSomething() {
        System.out.println("method");
    }

    public static void main(String[] args) {
        // the main method is the entry point for a program
        // inside methods the statements get executed in the order they appear in the code
        System.out.println("main one");
        OrderOfExecution example = new OrderOfExecution();
        System.out.println("main two");
        example.doSomething();
        System.out.println("main three");
    }
}
When executed this program outputs:

static initializer
main one
initializer
constructor
main two
method
main three

Resource Link: Stackoverflow

No comments:

Post a Comment