问题
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