`
uqortbsa
  • 浏览: 13991 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

初始化的实例

F# 
阅读更多
说明:包含main()方法的类中包含有static类,static类先初始化


class Bowl1 {
	Bowl1(int marker) {
		System.out.println("Bowl(" + marker + ")");
	}
	void f1(int marker) {
		System.out.println("f1(" +marker + ")");
	}
}

class Table1 {
	static Bowl1 bow1 = new Bowl1(1);
	Table1() {
		System.out.println("Table1()");
		bowl2.f1(1);
	}
	void f2(int marker) {
		System.out.println("f2(" + marker + ")");
	}
	static Bowl1 bowl2 = new Bowl1(2);
}

class Cupboard1 {
	Bowl1 bowl3 = new Bowl1(3);
	static Bowl1 bowl4=new Bowl1(4);
	Cupboard1() {
		System.out.println("Cupboard1()");
		bowl4.f1(2);
	}
	void f3(int marker) {
		System.out.println("f3(" + marker + ")");
	}
	static Bowl1 bowl5 = new Bowl1(5);
}
public class StaticInitialzation {
	public static void main(String[] args){
		System.out.println("Creating new CupBoard1() in main");
		new Cupboard1();
		System.out.println("Creating new CupBoard1() in main");
		new Cupboard1();
		table.f2(1);
		Cupboard.f3(1);
	}
	static Table1 table = new Table1();
	static Cupboard1 Cupboard = new Cupboard1();
}


结果:
Bowl(1)
Bowl(2)
Table1()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard1()
f1(2)
Creating new CupBoard1() in main
Bowl(3)
Cupboard1()
f1(2)
Creating new CupBoard1() in main
Bowl(3)
Cupboard1()
f1(2)
f2(1)
f3(1)
class B1 {

	void f(){
		System.out.println(1);
	}
}

class A1 {
	static B1 b;
	static {
		 b=new B1();
	}
	
	A1(){
		System.out.print("a");
	}
}
public class StaticInitialzation {
	public static void main(String args[]) {
	A1.b.f();
		
	}
}

静态初始化只有在必要时刻才会进行(不是说会自动初始化所有类中的静态变量或者静态块):
1.当第一引用类中的static变量时,所有的static变量和static块都会被初始化,类本身不会初始化(A1没有初始化)
2.创建类(B1)
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics