问题描述
- 网易类的初始化的笔试题
-
public class Father {public static String desc = "Father"; static { System.out.println(desc); } Father(){ System.out.println("Father Constructor"); } String str = fun(); public String fun(){ System.out.println("Father not static"); return "Father not static"; }
}
public class Child extends Father{ public static String desc = "Child"; static { System.out.println(desc); } Child(){ System.out.println("Child Constructor"); } String str = fun(); public String fun(){ System.out.println("Child not static"); return "Child not static"; } public static void main(String[] args) { Child c = new Child(); } }
请问输出是什么,为什么,
我测试的输出:
Father
Child
Child not static
Father Constructor
Child not static
Child Constructor
关于Father static为什么不出来我不懂,求帮助
解决方案
初始化顺序为:
类初始化:按出现顺序初始化静态类成员、static块
类实例初始化:按出现顺序初始化实例成员初始化和按规则调用构造方法
父类实例初始化过程中,由于实例化的是子类Child,父类的str对象在初始化过程中调用的fun()实际上是子类的重写方法,而并非父类声明的fun(),如果把父类的fun和子类的fun改为不同的简单名称,比如父类改为fun2(),那么就会输出Father not static而非Child not static
时间: 2024-08-31 05:21:38