派生类的类变量的初始化/实例化顺序和基类构造函数的调用

Order of initialization/instantiation of class variables of derived class and invoking of base class constructor(派生类的类变量的初始化/实例化顺序和基类构造函数的调用)

本文介绍了派生类的类变量的初始化/实例化顺序和基类构造函数的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚 1) 派生类变量的初始化/实例化 2) 在此代码段中调用基类构造函数的顺序

I want to figure out the order of 1) initialization/instatiation of derived class variables 2) invoking of base class constructor in this code snippet

public class base 
{
  int y = 1;
  public base()
  { 
      y = 2; 
      function();
  }
  void function () 
  {
     System.out.println("In base Value = " + String.valueOf(y));
  }

  public static class derived extends base 
  {
      int y = 3;
      public derived()
      { 
          function();
      }
      void function () 
      {
          System.out.println("In derived Value = " + String.valueOf(y));
      }
  }
  public static void main(String[] args) 
  { 
      base b = new base.derived();
      return;
  }
}

我的理解是,首先,派生类被实例化,然后基类构造函数被调用,然后派生类变量 y 被初始化.这个顺序正确吗?

my understadning is that first, derived class is instatiated, then base class constructor is called, then derived class variables y is initialized. Is this order correct?

推荐答案

执行顺序如下:

1) 静态初始化器

[基类实例化]

2) 实例初始化器

3) 构造函数

4) 主要的剩余部分.

4) The remainder of the main.

静态初始化在基类实例化之前.

Static initialisers precede base class instantiation.

如果您有超过 1 个实例初始化程序,它们会按照它们从上到下的写入顺序出现.

If you have more than 1 instance initialiser they occur in the order they are written in from top to bottom.

您没有任何实例块.

父类构造函数先运行,基类中的y变量设置为2,然后调用函数方法,但是函数方法在子类中被覆盖,所以使用子类方法.

The parent class constructor runs first, the y variable with in the base class is set to 2, the function method is then called, however the function method has been overridden in the subclass, hence the subclass method is used.

但是derived.y变量还没有初始化,所以y的值默认为0.

However the derived.y variable has not yet been initialized, hence the value of y is defaulted to 0.

之后,子类;然后派生的构造函数运行,派生.y的值被声明为3,派生类中定义的覆盖函数方法运行,因此打印派生值是3.

After that occurs, the sub-class; derived's constructor then runs, the value of derived.y is declared as 3 and the override function method defined in the derived class runs, hence printing the derived value is 3.

注意:两个y变量不相同.

Note: The two y variables are not the same.

这篇关于派生类的类变量的初始化/实例化顺序和基类构造函数的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:派生类的类变量的初始化/实例化顺序和基类构造函数的调用

基础教程推荐