2011年5月6日

建構區塊(constructor block)

if you miss to precede the block with "static" keyword, the block is called "constructor block" and will be executed when the class is instantiated. The constructor block will be copied into each constructor of the class. Say for example you have four parameterized constructors, then four copies of contructor blocks will be placed inside the constructor, one for each.

 
public class ConstructorBlock {
    public static void main(String[] args) {
        class ConstructorBlockExample
        {
            {
                System.out.println("This is first constructor block");
            }
   
            public ConstructorBlockExample(){
                System.out.println("This is no parameter constructor");
            }
   
            public ConstructorBlockExample(String param1){
                System.out.println("This is single parameter constructor");
            }
   
            public ConstructorBlockExample(String param1, String param2){
                System.out.println("This is two parameters constructor");
            }
   
            {
                System.out.println("This is second constructor block");
            }
        }
       
        ConstructorBlockExample cb1 = new ConstructorBlockExample();
        ConstructorBlockExample cb2 = new ConstructorBlockExample("2");
        ConstructorBlockExample cb3 = new ConstructorBlockExample("","");
    }
   
}


結果 :


This is first constructor block
This is second constructor block
This is no parameter constructor
This is first constructor block
This is second constructor block
This is single parameter constructor
This is first constructor block
This is second constructor block
This is two parameters constructor

沒有留言:

ShareThis