作者TonyQ (自立而後立人)
看板java
标题Re: [问题] Class中的大括号
时间Thu Jun 26 02:28:44 2014
※ 引述《Lest ()》之铭言:
: class A {
: {
: System.out.println("123");
: }
: public A(){
: System.out.println("345");
: }
: }
: 请问一下JAVA高手,我学过的JAVA Class内只能包含建构子、方法及变数
: 那为何我的Class A又可以存在一个大括号。
: 当我new A(); 会显示如下:
: 123
: 345
: 为何大括号的123会执行呢????
这个其实官网教学中有提到,概略翻译一下应该就蛮能理解的。
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Normally, you would put code to initialize
an instance variable in a constructor.
There are two alternatives to using a constructor to
initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static initializer
blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor.
Therefore, this approach can be used to share a block of code between
multiple constructors.
一般来说你应该把初始化一个变数成员的行为放在 constructor,
但还是有其他两个方法可以应用,其中一个就是你提到的这个初始化 block。
它会把这个 {} 里面的程式码放进每个建构子里面,
这样就可以用来在多个建构子里面共用程式码。
(但我个人是不会建议这麽做就是了。)
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.231.162.229
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/java/M.1403720926.A.E71.html
1F:推 popcorny:推!! instance init比较少用..static init倒是比较常用 06/26 09:49
2F:推 Deltaguita:感谢新板主讲解,话说现在这个标题可以换掉吗? 06/26 10:10
3F:→ Deltaguita:有一种被放嘲讽的感觉 06/26 10:16
4F:→ realmeat:疑? 版主换人了 06/26 11:49
5F:→ TonyQ:这当然,马上来处理 XD 06/26 11:53
6F:推 lovelycateye:咦?我还以为我来到 Ajax 版 06/26 12:13
7F:→ NullLife:(笔记) 06/26 23:59
8F:→ cha122977:一段时间没来版主真的换人了OAOa 06/28 17:34