gpt4 book ai didi

java - Java 中的数据绑定(bind)覆盖

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:15:41 24 4
gpt4 key购买 nike

我是java初学者,我写了下面的代码

class SuperA{
Integer a = 1;
protected void f(){
System.out.println("in superA");
}
}

class Test extends SuperA{
Integer a = 2;
protected void f(){
System.out.println("in test");
}

public static void main(String... args) throws Exception{

SuperA o = new Test();
o.f();
System.out.println("a = "+o.a);
}
}

Output: in test

a = 1

我知道为什么它是in test。但不明白为什么a=1。我认为它应该是 a=2

多态中调用方法和数据有什么区别?

最佳答案

class SuperA{
Integer a = 1;

class Test extends SuperA{
Integer a = 2;

您的Test 类拥有两个名为a 的独立实例变量。它们可以访问为

this.a

((SuperA)this).a

这使得它们不同于方法,其中 Test 中定义的 f() overrides SuperA 中的方法, 所以 Test 不拥有父类(super class)版本。

关于java - Java 中的数据绑定(bind)覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21091247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com