Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...