打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
继承关系中类成员的初始化
userphoto

2013.03.04

关注


public class House {
 public House(String name){
  System.out.println(name+" 's house");
 }
}

public class GrandFather{
 protected GrandFather(){
  System.out.println("GrandFather()");
 }
 
 static{
  System.out.println("static block in GrandFather");
 }
 
 {
  System.out.println("initialization in GrandFather");
 }
 
 static House h1 = new House("static GrandFather");
 
 House h2 = new House("GrandFather");
}

public class Father extends GrandFather{
 
 static {
  System.out.println("static block in Father");
 }
 
 static House h1 = new House("static Father");
 
 protected Father(){
  System.out.println("Father()");
 }
  
 {
  System.out.println("initialization in Father");
 }
}

public class son extends Father{

 son() {
  System.out.println("son()");
        }

 public static void main(String[] args) {
  System.out.println("********entry in main********");
  new son();
 }
 
 static House h1 = new House("static son");
 
 static{
  System.out.println("static block in son");
 }
 
 House h2 = new House("son");
 
 {
  System.out.println("block in son");
 }
 
}

运行结果:

static block in GrandFather
static GrandFather 's house
static block in Father
static Father 's house
static son 's house
static block in son
********entry in main********
initialization in GrandFather
GrandFather 's house
GrandFather()
initialization in Father
Father()
son 's house
block in son
son()

结论:
在继承关系中,类成员的初始化遵照以下顺序

①最外层超类的静态成员
②超类静态成员
③子类静态成员
④最外层超类的非静态成员
⑤最外层超类的构造器
⑥超类的非静态成员
⑦超类的构造器
⑧子类的非静态成员
⑨子类构造器

其中,相同类型(同为静态或者非静态成员)复数成员的初始化,遵照其在代码中出现的顺序。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java类初始化顺序
父类和子类,实例、静态成员变量,构造函数的执行顺序
方法的多态static理解 与 static方法(与隐式static方法)
java构造方法和new关键字
JAVA中初始化顺序复习
static变量是否能继承详细介绍
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服