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.
这篇关于派生类的类变量的初始化/实例化顺序和基类构造函数的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:派生类的类变量的初始化/实例化顺序和基类构造函数的调用
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01