{
c1 = new Mug(1);
c2 = new Mug(2);
System.out.println("c1 & c2 initialized");
}
在上面的代码中为什么 System.out.println("c1 & c2 initialized");也可以运行
整个代码如下:class Mug {
Mug(int er) {
System.out.println("Mug(" + er + ")");
}
void f(int er) {
System.out.println("f(" + er + ")");
}
}public class Mugs { Mug c1;
Mug c2;
{
c1 = new Mug(1);
c2 = new Mug(2);
System.out.println("c1 & c2 initialized");
}
Mugs() {
System.out.println("Mugs()");
}
public static void main(String[] args) {
System.out.println("Inside main()");
Mugs x = new Mugs();
/*monitor.expect(new String[] {
"Inside main()",
"Mug(1)",
"Mug(2)",
"c1 & c2 initialized",
"Mugs()"
});*/
}
}
c1 = new Mug(1);
c2 = new Mug(2);
System.out.println("c1 & c2 initialized");
}
在上面的代码中为什么 System.out.println("c1 & c2 initialized");也可以运行
整个代码如下:class Mug {
Mug(int er) {
System.out.println("Mug(" + er + ")");
}
void f(int er) {
System.out.println("f(" + er + ")");
}
}public class Mugs { Mug c1;
Mug c2;
{
c1 = new Mug(1);
c2 = new Mug(2);
System.out.println("c1 & c2 initialized");
}
Mugs() {
System.out.println("Mugs()");
}
public static void main(String[] args) {
System.out.println("Inside main()");
Mugs x = new Mugs();
/*monitor.expect(new String[] {
"Inside main()",
"Mug(1)",
"Mug(2)",
"c1 & c2 initialized",
"Mugs()"
});*/
}
}
class Test
{
B b = new B();
}等价于
class Test
{
B b; {
b = new B();
}
}也等价于
class Test
{
B b;
public Test()
{
b = new B();
}
}
1.静态变量初始化:Java能让你用特殊的“static”子句把其它的静态初始化语句全部组织起来。它的形试是这样的:
static int i;
static int j;
static{
i=47;
j=48;
}
看上去像是一个方法,但实际上只是一段跟在"static"关键词后面的代码。同别的static的初始化一样,这些代码只会执行一次;
2.非静态的初始化;Java提供了一种类似的语法来初始化非static的变量。除了没有static关键词,同静态初始化没有什么两样。这种语法有特殊的用途。详见Thinging In Java
楼主的初始化的代码:
Mug c1;
Mug c2;
{
c1 = new Mug(1);
c2 = new Mug(2);
System.out.println("c1 & c2 initialized");
}
紧跟着的花括花是一个语句块,里面的内容是对上面的初始化工作,这是一种语法现像。整个语句块是为变量(对象)初始化用的,因此,整个语句都要执行。
//你的代码和Thing In Java 的一样---第四章,看看书便知。如果没有此类书,可到我的blog
//去下:www.sunnymoon.boke.in
{ }可使用非静态的变量
如上例:{this.c1=new Mug(1);this.c2=new Mug(2);System.out.println("c1&c2 initialized");}
其实这种用法的主要用途是为匿名内部类初始化用的,为它提供了不.要.中少的支持。
再看看一些相关的内容吧。
其实这种用法的主要用途是为匿名内部类初始化用的,为它提供了必不可少的支持。
再看看一些相关的内容吧。
我再给分
http://community.csdn.net/Expert/topic/4898/4898648.xml?temp=.1511347