繼承與static
public class Test extends Y {
Test(String str) {
super(str);
// TODO Auto-generated constructor stub
}
Y y = new Y("Test");
static {
System.out.println("tttt");
}
public static void main(String[] args) {
new Z("mian");
}
}
class Y {
static {
System.out.println("t");
}
Y(String str) {
System.out.println("Y - " + str);
}
}
class Z extends Test {
Y y = new Y("Z");
static {
System.out.println("tt");
}
Z(String str) {
super(str);
System.out.println("Z");
}
}
輸出結果是:
大概的Java載入順序爲:
main--->父類 --- >static--->父類屬性--->父構造函數--->自己屬性--->自己構造函數
爲什麼要用static?
方便在沒有創建對象的情況下來進行調用(方法/變量)。
靜態方法中不能訪問非靜態成員方法和非靜態成員變量,但是在非靜態成員方法中是可以訪問靜態成員方法/變量的
static變量
static變量也稱作靜態變量,靜態變量和非靜態變量的區別是:靜態變量被所有的對象所共享,在內存中只有一個副本,它當且僅當在類初次加載時會被初始化。而非靜態變量是對象所擁有的,在創建對象的時候被初始化,存在多個副本,各個對象擁有的副本互不影響
參考:
http://www.cnblogs.com/dolphin0520/p/3799052.html