java继承与初始化
類文件:Print.java
package net.mindview.util;
import java.io.*;
public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
}
類文件:Beetle.java
import static net.mindview.util.Print.*;
class InsectInit {
private int k = printInit("InsectInit.k initialized");
private int i = 10;
protected int j;
InsectInit() {
print("i = " + i + ", j = " + j);
j = 40;
}
private static int x3 = printInit("static Insect.x3 initialized");
static int printInit(String s) {
print(s);
return 48;
}
}
?
class Insect extends InsectInit {
private int k = printInit("Insect.k initialized");
private int i = 9;
protected int j;
Insect() {
print("i = " + i + ", j = " + j);
j = 39;
}
private static int x1 = printInit("static Insect.x1 initialized");
static int printInit(String s) {
print(s);
return 47;
}
}
public class Beetle extends Insect {
private int k = printInit("Beetle.k initialized");
public Beetle() {
print("k = " + k);
print("j = " + j);
}
private static int x2 = printInit("static Beetle.x2 initialized");
public static void main(String[] args) {
print("Beetle constructor");
Beetle b = new Beetle();
}
}
/*Output:
static Insect.x3 initialized
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
InsectInit.k initialized
i = 10, j = 0
Insect.k initialized
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
*/
?
從輸入中可以看出初始化順序是:
頂層基類static屬性--->第二層基類static屬性--->導(dǎo)出類static屬性--->main方法--->頂層基類屬性--->頂層基類構(gòu)造方法--->第二層基類屬性--->第二層基類構(gòu)造方法--->子類屬性--->子類構(gòu)造方法
轉(zhuǎn)載于:https://www.cnblogs.com/shengwuzhongzi/p/5667986.html
總結(jié)
以上是生活随笔為你收集整理的java继承与初始化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gvim 编辑器初学
- 下一篇: synchronized的理解