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属性--->导出类static属性--->main方法--->顶层基类属性--->顶层基类构造方法--->第二层基类属性--->第二层基类构造方法--->子类属性--->子类构造方法

转载于:https://www.cnblogs.com/shengwuzhongzi/p/5667986.html


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部