gpt4 book ai didi

java - 子类不更新从基类获取的变量

转载 作者:行者123 更新时间:2023-12-01 22:15:19 24 4
gpt4 key购买 nike

为什么我的输出没有给出预期的结果,即25?我知道我的问题很愚蠢,但我是 Java 编程新手。输出是

run:
5
0
0
BUILD SUCCESSFUL (total time: 0 seconds)

但根据我的预期答案是 5,因为我在争论中已经通过了 5。

class A {
int a;

public void setA(int a) {
this.a = a;
}
}

class B extends A {
public int multi() {
int multi = a * a;
System.out.println(multi);
return multi;
}
}

class test {
public static void main(String[] args) {
A obj1 = new A();
obj1.setA(5);
B obj2 = new B();
int c = obj2.multi();
System.out.println(c);
}
}

最佳答案

why output is not giving expected result i.e. 25

因为你有两个不同的对象,每个对象都有一个独立的a字段。您在一个对象中将值设置为 5,然后在另一个对象上调用 multi(),因此它使用字段的默认值 (0)。

如果您对两个部分使用相同的对象,您将得到正确的答案:

B obj2 = new B();
A obj1 = obj2; // Now obj1 and obj2 refer to the same object
obj1.setA(5);
System.out.println(obj2.multi());

关于java - 子类不更新从基类获取的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31189817/

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