gpt4 book ai didi

Java:为什么结果是5而不是10?

转载 作者:行者123 更新时间:2023-12-01 06:36:31 27 4
gpt4 key购买 nike

设 A.java 文件为:

    class B {static int i; }

class A {
public static void main(String[] args) {
B a=new B();
B b=new B();
a.i=10;
b.i=5;

System.out.println(a.i);
}
}

为什么结果是 5 而不是 10?

谢谢。

最佳答案

因为你的变量是静态的。这意味着它与类型相关,而不是与该类型的任何特定实例相关。您的代码相当于:

// These are actually ignored as far as the subsequent lines are concerned.
// The constructor will still be executed, but nothing is going to read the
// values of variables "a" and "b".
B a = new B();
B b = new B();

// Note this is the *type name*.
B.i = 10;
B.i = 5;
System.out.println(B.i);

在我看来,允许通过这样的表达式访问静态成员是一个设计错误 - 在某些 IDE(例如 Eclipse)中,如果您愿意,它最终可能会发出警告甚至错误。

关于Java:为什么结果是5而不是10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7761191/

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