static初始化问题

个人见解:static只初始化一次,后面的都是引用

package fifthChapter;

public class Bowl {
	public Bowl(int marker){
		System.out.println("Bow1("+marker+")");
	}
	void f(int marker){
		System.out.println("f("+marker+")");
	}
}

package fifthChapter;

public class Table {
	static Bowl b1 = new Bowl(1);
	Table(){
		System.out.println("Table()");
		b2.f(1);
	}
	void f2(int marker){
		System.out.println("marker("+marker+")");
	}
	static Bowl b2 = new Bowl(2);
}

package fifthChapter;

public class CupBoard {
	Bowl b3 = new Bowl(3);
	static Bowl b4 = new Bowl(4);
	CupBoard(){
		System.out.println("CupBoard()");
		b4.f(2);
	}
	void f3(int marker){
		System.out.println("f3("+marker+")");
	}
	static Bowl b5 = new Bowl(5);
}

package fifthChapter;

public class StaticDemo {
	public static void main(String[] args) {
		CupBoard.b4.f(4);	//不会执行Table b3 = new Tabel(3);
		System.out.println("Create new CupBoard() in main");
		new CupBoard();		//Table b3 = new Tabel(3)会执行
		System.out.println("\nCreate new CupBoard() in main");
		new CupBoard();
		System.out.println("\nt2之后:");
		t2.f2(1);
		System.out.println("\nt2之后:");
		t3.f3(1);
	}
	static Table t2 = new Table();			//会初始化未初始化的static对象,会执行Table b3 = new Tabel(3),会执行构造器中的内容
	static CupBoard t3 = new CupBoard();	//会初始化未初始化的static对象,会执行Table b3 = new Tabel(3),会执行构造器中的内容
}

衷心建议main中的语句一条一条运行看结果

总结:

  1. static的存在优先于对象
  2. 倒数t2和t3语句都会初始化类内部的未初始化对象,会new对象,也会执行构造器
  3. new CupBoard();会初始化类内部的未初始化对象,会new对象,也会执行构造器
  4. 单纯的类名.static对象(CupBoard.b4.f(4);)只会初始化static对象
  5. 初始化过的static对象,就不再重复初始化;如可以new CupBoard()new两次看bowl(4),bowl(5)是否出现两次

你可能感兴趣的:(JAVA)