java 初始化object_Object Initialization in Java(Java的对象初始化)

多说无益,直接看代码。

public classMyTest {public static voidmain(String[] args)

{

Test t1= newTest();

System.out.println("------------");

Test t2= new Test(11);

System.out.println("------------");

}

}classTest

{private static int b =initializeB();private static int a =initializeA();private int c =initializeC();private static intinitializeA()

{

System.out.println("Initialize a in private static method");return 1;

}private static intinitializeB()

{

System.out.println("Initialize b in private static method");return 1;

}protected final intinitializeC()

{

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");

}publicTest()

{

System.out.println("In the constructor without parameter");

}public Test(intuseless)

{

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)

原文:http://www.cnblogs.com/neweracoding/p/4199192.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值