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


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01