Initialization in polymorphism of variables(变量多态的初始化)
问题描述
假设你有以下代码
class A {
int i = 4;
A() {
print();
}
void print () {
System.out.println("A");
}
}
class B extends A {
int i = 2; //"this line"
public static void main(String[] args){
A a = new B();
a.print();
}
void print () {
System.out.println(i);
}
}
这将打印 0 2
现在,如果您删除标有此行"的行代码将打印 4 4
Now, if you remove line labeled "this line" the code will print 4 4
- 我明白如果没有 int i=2;线,
A a = new B();会调用A类,初始化i为4,调用构造函数,
控制 class B 中的 print() 方法,最后打印 4.
A a = new B(); will call class A, initializes i as 4, call constructor,
which gives control over to print() method in class B, and finally prints 4.
a.print() 将调用 B 类中的 print() 方法,因为这些方法将在运行时绑定,这也将使用在 A 类中定义的值,4.
a.print() will call print() method in class B because the methods will bind at runtime, which will also use the value defined at class A, 4.
(当然如果我的推理有任何错误,请告诉我)
(Of course if there is any mistake in my reasoning, let me know)
- 但是,我不明白是否存在 int i=2.
为什么如果插入代码,第一部分(创建对象)会突然打印 0 而不是 4?为什么不将变量初始化为i=4,而是赋值为默认值?
why is it that if you insert the code, the first part (creating object) will all of sudden print 0 instead of 4? Why does it not initialize the variable as i=4, but instead assigns default value?
推荐答案
它是Java中几种行为的组合.
It is a combination of several behaviors in Java.
- 方法覆盖
- 实例变量阴影
- 构造函数的顺序
我将简单地回顾一下你的代码中发生的事情,看看你是否理解.
I will simply go through what happened in your code, and see if you understand.
您的代码在概念上如下所示(跳过 main()):
Your code conceptually looks like this (skipping main()):
class A {
int i = 0; // default value
A() {
A::i = 4; // originally in initialization statement
print();
}
void print () {
System.out.println("A");
}
}
class B extends A {
int i = 0; // Remember this shadows A::i
public B() {
super();
B::i = 2;
}
void print () {
System.out.println(i);
}
}
所以,当在你原来的main()中,你调用了A a = new B();,它正在构造一个B,发生这种情况:
So, when in your original main(), you called A a = new B();, it is constructing a B, for which this happens:
A::i和B::i都是默认值0- super(),表示调用A的构造函数
A::i设置为 4print()被调用.由于后期绑定,绑定到B::print()B::print()正在尝试打印出B::i,它仍然是 0
A::iandB::iare all in default value0- super(), which means A's constructor is called
A::iis set to 4print()is called. Due to late-binding, it is bound toB::print()B::print()is trying to print outB::i, which which is still 0
然后,当您在
main()中调用a.print()时,它会绑定到B::print()哪个正在打印出B::i(此时为 2).Then when you call
a.print()in yourmain(), it is bounded toB::print()which is printing outB::i(which is 2 at this moment).因此你看到的结果
这篇关于变量多态的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:变量多态的初始化
基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
