gpt4 book ai didi

Java静态混淆

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:42 24 4
gpt4 key购买 nike

我正在使用 Java;我以前使用过 C++。我正在考虑 Java 中的静态用法。如果我在类中创建静态方法和变量,为什么我也可以通过对象访问它们?

例子:

class Test{
static int count=0;
int id;
static void updatec(){
count++
}
}

class TestMain
{
public static void main(String args[])
{
Test.count=1;
Test t = new Test();
t.count=5; // Valid WHY ?????
}
}

为什么这是允许的? Java 的网站说我们不应该使用 obj.static 方法/变量。
为什么允许?

最佳答案

静态并不意味着该字段仅适用于该类。这意味着类及其所有实例

In this example, the class variable origin of the class Point is referenced both using the class name as a qualifier, in Point.origin, and using variables of the class type in field access expressions (§15.11), as in p.origin and q.origin. These two ways of accessing the origin class variable access the same object, evidenced by the fact that the value of the reference equality expression (§15.21.3):
q.origin==Point.origin is true

但你是对的,从非静态上下文中引用静态字段/方法/类通常不是一个好主意,它会使开发人员感到困惑。


资源:

关于Java静态混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3610309/

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