Order of initialization/instantiation of class variables of derived class and invoking of base class constructor

醉酒当歌 提交于 2020-01-16 05:34:05

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32490714/order-of-initialization-instantiation-of-class-variables-of-derived-class-and-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!