gpt4 book ai didi

java - 为什么对象可以改变类变量的值?

转载 作者:行者123 更新时间:2023-11-29 09:34:27 25 4
gpt4 key购买 nike

由 Oracle 的 definition ,

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.

根据这个定义,可以安全地推断出静态变量属于该类并且不应被该类的任何对象访问以进行修改。因为所有对象都共享它。

所以来自同一定义的这一行有点令人困惑:

Any object can change the value of a class variable...

所以我尝试了这段代码并打印了 45(尽管我收到一条警告说“通过实例引用访问静态成员”):

public class Main {

static int value = 8;

public static void main(String[] args) {
// write your code here

Main main = new Main();

main.value = 45;

System.out.println(value);
}
}

如果这是一个 Student 类,并且我有一个名为 numberOfStudents 的静态变量,为什么应该允许该类的一个对象更改此类变量的值?

最佳答案

真的“一个对象”可以——只是你在可以访问该变量的代码中,不幸的是,Java 允许你访问静态成员(包括变量和方法)如果他们是实例成员。这最终会产生非常具有误导性的代码,例如

Thread t = new Thread(...);
t.start();
t.sleep(1000);

最后一行看起来要求新启动的线程 hibernate - 但实际上它会让当前线程 hibernate 。

这基本上是 Java 的一个缺陷。编译器会默默地将这样的代码变成

Thread.sleep(1000);

或者在你的情况下

Main.value = 45;

(我相信在旧版本的 Java 中,它会发出代码来检查您“通过”访问静态成员的变量是否为空,但它甚至不再这样做了。)

许多 IDE 允许您用警告或错误标记这样的代码。我鼓励您打开这样的功能。如果您看到这样的现有代码,请将其更改为直接通过声明类访问静态成员,这样就很清楚发生了什么。

关于java - 为什么对象可以改变类变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29050441/

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