标签:内部类 sys 执行 bsp public 关键字 java main sid
Java中也有被称为实例初始化的类似语法,用来初始化每一个对象的非静态变量。例如:
//: initialization/Mugs.java
// Java "Instance Initialization."
class Mug {
Mug(int marker) {
System.out.println("Mug(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
public class Mugs {
Mug mug1;
Mug mug2;
{
mug1 = new Mug(1);
mug2 = new Mug(2);
System.out.println("mug1 & mug2 initialized");
}
Mugs() {
System.out.println("Mugs()");
}
Mugs(int i) {
System.out.println("Mugs(int)");
}
publis static void main(String[] args) {
System.out.println("Inside main()");
new Mugs();
System.out.println("new Mugs() completed");
new Mugs(1);
System.out.println("new Mugs(1) completed");
}
} /* Output:
Mug(1)
Mug(2)
mug1 & mug2 initialized
Mugs()
new Mugs() completed
Mug(1)
Mug(2)
mug1 & mug2 initialized
Mugs(int)
new Mugs(1) completed
*///:~
这里面的实例初始化子句:
{
mug1 = new Mug(1);
mug2 = new Mug(2);
System.out.println("mug1 & mug2 initialized");
}
看起来它与静态初始化子句一模一样,只不过少了static关键字,这种语法对于支持“匿名内部类”的初始化是必须的,但是它也使得你可以保证无论调用了哪个显示构造器,某些操作都会发生。从输出中可以看到实例初始化子句事在两个构造器之前执行的。
标签:内部类 sys 执行 bsp public 关键字 java main sid
原文地址:http://www.cnblogs.com/deriito/p/6295114.html