类中代码块,静态代码块,变量,静态变量,构造方法的加载顺序
1.父类
public class StaticParentTest {
int parentInit = parentInit();
static int staticParentInit = staticParentInit();
{
System.out.println("父类代码块");
}
static {
System.out.println("父类静态代码块");
}
StaticParentTest() {
System.out.println("父类构造方法");
}
void parentPrint(){
System.out.println("父类方法");
}
static void staticParentPrint(){
System.out.println("父类静态方法");
}
int parentInit() {
System.out.println("父类变量");
return 1;
}
static int staticParentInit() {
System.out.println("父类静态变量");
return 1;
}
}
2.子类
public class StaticTest extends StaticParentTest {
{
System.out.println("子类代码块");
}
static {
System.out.println("子类静态代码块");
}
int init = init();
static int staticInit = staticInit();
StaticTest() {
System.out.println("子类构造方法");
}
void print(){
System.out.println("子类方法");
}
static void staticPrint(){
System.out.println("子类静态方法");
}
int init() {
System.out.println("子类变量");
return 1;
}
static int staticInit() {
System.out.println("子类静态变量");
return 1;
}
}
3.调用类
public static void main(String[] args) {
StaticParentTest staticParentTest = new StaticParentTest();
System.out.println("----------------------------------");
StaticTest staticTest = new StaticTest();
System.out.println("----------------------------------");
StaticParentTest test = new StaticTest();
System.out.println("----------------------------------");
StaticParentTest.staticParentPrint();
StaticTest.staticPrint();
staticParentTest.parentPrint();
staticTest.print();
System.out.println("----------------------------------");
System.out.println(test.getClass() == StaticParentTest.class);
System.out.println(test.getClass() == StaticTest.class);
System.out.println(test instanceof StaticParentTest);
System.out.println(test instanceof StaticTest);
}
4.结果
![](https://i-blog.csdnimg.cn/blog_migrate/f77174ba703aa11b179d130c08560d20.png)
需要注意的有两点:
- 静态代码块与静态变量为同时加载,具体加载顺序取决于谁写在前面
- 判断对象类型,用反射的方式比较时,当且仅当类型全等时才为true,用instanceof判断时,类的继承链上所有的父类直到Object都会判断为true
如有错误请指出
参考:
如何判断对象的类型(java)