Object Initialization in Java(Java的对象初始化)

多说无益,直接看代码。

public class MyTest {
    public static void main(String[] args)
    {
        Test t1 = new Test();
        System.out.println("------------");
        Test t2 = new Test(11);
        System.out.println("------------");
    }    
}

class Test
{
    private static int b = initializeB();
    private static int a = initializeA();
    private int c = initializeC();
    
    private static int initializeA() 
    {        
        System.out.println("Initialize a in private static method");
        return 1;
    }
    
    private static int initializeB() 
    {        
        System.out.println("Initialize b in private static method");
        return 1;
    }
    
    protected final int initializeC() 
    {        
        System.out.println("Initialize c in private method for each object");
        return 1;
    }
    
    static //Only called once at class load time
    {
        System.out.println("C# Static Constructor Equivalent\n====Static Initialization is done====");
    }

    //Called every time before the constructor
    //This is shared among all the constructors.
    {
        System.out.println("Non-static shared block");
    }    
    
    public Test()
    {
        System.out.println("In the constructor without parameter");
    }
    
    public Test(int useless)
    {
        System.out.println("In the constructor with only 1 parameter");
    }
}

 

Console:

Initialize b in private static method
Initialize a in private static method
C# Static Constructor Equivalent
====Static Initialization is done====
Initialize c in private method for each object
Non-static shared block
In the constructor without parameter
------------
Initialize c in private method for each object
Non-static shared block
In the constructor with only 1 parameter
------------

 

Double Brace Initialization:

See:  http://www.c2.com/cgi/wiki?DoubleBraceInitialization

The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an "instance initializer", because it is declared within the instance scope of the class -- "static initializers" are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class (specified at http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.6) The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors (but not before superclass constructors)

posted @ 2015-01-03 10:24  新一代的天皇巨星  阅读(623)  评论(0编辑  收藏  举报