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

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

问题描述

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

 公共类别基础
{
int y = 1;
public base()
{
y = 2;
function();
}
void函数()
{
System.out.println( In base Value = + String.valueOf(y));
}

派生的公共静态类扩展了基础
{
int y = 3;
public metadata()
{
function();
}
无效函数()
{
System.out.println( In得出的值= + String.valueOf(y));
}
}
public static void main(String [] args)
{
base b = new base.derived();
的回报;
}
}

我的低估是,首先,派生类被实例化,然后调用基类构造函数,然后初始化派生类变量y。此命令正确吗?

解决方案

执行顺序按以下方式发生:



1)静态初始值设定



[基类实例化]



2)实例初始值设定



3)构造函数



4)其余的主体。



静态初始化程序在基类实例化之前。



如果实例初始化程序超过1个,则它们按照从上到下的顺序进行写。 / p>




您的代码



您没有任何实例块。



父类构造函数首先运行,基类中的y变量设置为2,然后调用函数方法,但是该函数方法已被覆盖



但是$ y $变量尚未初始化,因此y的值默认为0



在这种情况下,该子类为;然后派生的构造函数运行,派生的y的值声明为3,并且派生类中定义的重写函数方法运行,因此打印派生的值为3。



注意:这两个y变量不同。


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;
  }
}

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?

解决方案

The order of execution occurs in the following manner:

1) Static initializers

[Base class instantiation]

2) Instance initializers

3) The constructor

4) The remainder of the main.

Static initialisers precede base class instantiation.

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


Your code

You do not have any instance blocks.

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.

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

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.

Note: The two y variables are not the same.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆