Java中的向上转换和两个单独的对象属性 [英] Upcasting in Java and two separate object properties
问题描述
尝试理解Java中的upcasting。最近观察到的奇怪行为。
Trying to understand upcasting in Java. Recently observed strange behavior.
示例:
public class A extends B {
public int i = 2;
public void printI() {
System.out.println("print i = " + this.i);
}
public static void main(String[] args) {
B a = new A(); // <- upcasting here
System.out.println("i = " + a.i);
a.printI();
}
}
class B {
public int i = 1;
public void printI() {}
}
//Output:
//i = 1
//print i = 2
似乎,upcasted对象有两个独立的i属性。一个i直接访问(ai),另一个通过子类(a.printI())的方法访问。
Seems, that upcasted object has two separate "i" properties. One "i" accessible directly (a.i) and the other through methods of child class (a.printI()).
看起来upcasted对象从超类和方法获取属性来自子类。
Looks like upcasted object gets properties from superclass and methods from child class.
对象如何有两个单独的i?!
How object can have two separate "i"s?!
推荐答案
似乎,upcasted对象有两个独立的i属性。
Seems, that upcasted object has two separate "i" properties.
首先,值得明确术语。在 A
和 B中,每个
和
都没有upcasted object和i是字段
。
Firstly, it's worth being clear about terminology. There's no such thing as an "upcasted object" - and "i" is a field in each of A
and B
.
但是,这里有两个单独的字段。它不像一个字段覆盖另一个或类似的东西。
But yes, there are two separate fields here. It's not like one field "overrides" another or anything like that.
目前还不清楚你尝试实现了什么,但声明 i
in A
阴影 i $的声明c $ c> in
B
。有关更多信息,请参阅 Java语言规范的第6.4节信息。
It's not clear what you were trying to achieve, but the declaration of i
in A
shadows the declaration of i
in B
. See section 6.4 of the Java Language Specification for more information.
请注意,在几乎所有情况下,字段都应该是私有的 - 此时隐藏真的无关紧要,因为您不会尝试引用无论如何都没有在你编码的类中声明的变量。
Note that in almost all cases, fields should be private - at which point the hiding really doesn't matter, as you wouldn't try to refer to a variable which wasn't declared in the class you're coding in anyway.
这篇关于Java中的向上转换和两个单独的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!