Wednesday, September 24, 2014

[Java] An example of initialization block

This is an example from Oracle’s official site and good for learning the initialization block.
If you want know more about initializing fields, you can visit these links:

http://terrapinssky.blogspot.hk/2014/09/javatutorial-initializer-initialization.html
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

public class Sequence {
    Sequence() { System.out.print("c "); }
    { System.out.print("y "); }
    public static void main(String[] args) {
        new Sequence().go();
    }
    void go() { System.out.print("g "); }
    static { System.out.print("x "); }
}

 Result:



Explanation:  
1    public class Sequence {
2              Sequence() { System.out.print("c "); }
3              { System.out.print("y "); }
4              public static void main(String[] args) {
5                       new Sequence().go();
6               }
7              void go() { System.out.print("g "); }
8             
9              static { System.out.print("x "); }
10    }


Since this line (line9) is an static initialization block and called when the class is loaded.
    static { System.out.print("x "); }
So when the class Sequence with main method is loaded, this static initialization was called first (before the constructor starts)
And then in the main method, the code (at line6):
    new Sequence()
create a Sequence Object so it would called the Sequence’s constructor. However, before the Sequence’s constructor run, the initialization block (at line3):
    { System.out.print("y "); }
is an initialization block, and the code is copied into the beginning of the constructor of the class. So it’s the reason why the “y” is printed before “c”, code in the initialization block ({ System.out.print("y "); } )runs before the code (System.out.print("c ");) placing in constructor.

Since an Sequence object created, we call the go() method of that and run the “System.out.print("g ");”  at line8. So the last character in the result in a "g".

 
    Result: xycg
Reference:

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
http://stackoverflow.com/questions/13699075/calling-a-java-method-with-no-name
https://community.oracle.com/thread/2522199?tstart=0

No comments :

Post a Comment