疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java类中继承与初始化


 

   

  Java类中继承与初始化(包含static)

  package cm.java.Practic7;

  class Insect {

  private int i = 9;

  protected int j;

  Insect() {

  System.out.println("i = " + i + ",j = " + j);

  j = 39;

  }

  private static int x1 = printInit("static Insect.x1 initialized");

  static int printInit(String s) {

  System.out.println(s);

  return 47;

  }

  }

  public class InitWithExtendP146 extends Insect {

  private int k = printInit("InitWithExtendP146.k initialized");

  public InitWithExtendP146() {

  System.out.println("k = " + k + ",j =" + j);

  }

  private static int x2 = printInit("static InitWithExtendP146.x2 initialized");

  public static void main(String[] args) {

  System.out.println("InitWithExtendP146 constructor");

  InitWithExtendP146 b = new InitWithExtendP146();

  }

  }

  输出的结果:

  static Insect.x1 initialized

  static InitWithExtendP146.x2 initialized

  InitWithExtendP146 constructor

  i = 9,j = 0

  InitWithExtendP146.k initialized

  k = 47,j =39

  总结如下:

  先statc的数据成员,再static的方法;

  先基类的数据成员,构造函数,再自己的数据成员,构造函数。

  过程如下:

  1 首先:寻找InitWithExtendP146类中的mian函数,发现该类中static的数据成员

  所以首先加载静态数据成员,然后发现该类是继承于Insect,

  所以首先加载基类中的static数据成员

  private static int x1 = printInit("static Insect.x1 initialized");

  输出:static Insect.x1 initialized

  接着加载自己的数据成员

  private static int x2 = printInit("static InitWithExtendP146.x2 initialized");

  输出:static InitWithExtendP146.x2 initialized

  2 静态函数:mian函数

  System.out.println("InitWithExtendP146 constructor");

  输出:InitWithExtendP146 constructor

  然后:

  InitWithExtendP146 b = new InitWithExtendP146();

  这里,首先就是执行构造函数,首先基类的构造函数:

  Insect() {

  System.out.println("i = " + i + ",j = " + j);

  j = 39;

  }

  输出:i = 9,j = 0

  接着自己的数据成员:

  private int k = printInit("InitWithExtendP146.k initialized");

  输出:InitWithExtendP146.k initialized

  然后构造函数:

  public InitWithExtendP146() {

  System.out.println("k = " + k + ",j =" + j);

  }

  输出:k = 47,j =39

  所以整个输出:

  static Insect.x1 initialized

  static InitWithExtendP146.x2 initialized

  InitWithExtendP146 constructor

  i = 9,j = 0

  InitWithExtendP146.k initialized

  k = 47,j =39