java - 将实例变量分配给静态变量

标签 java static

我有这样的东西:

public class Test {

    public static MyObject o4All = null;

    public MyObject o4This = null;

    public void initialize() {

        // create an instance of MyObject by constructor
        this.o4This = new MyObject(/* ... */);

        // this works, but I am wondering
        // how o4All is internally created (call by value/reference?)
        Test.o4All = this.o4This;

    }
}

我知道,我应该只通过静态方法分配或更改静态变量。但是根据 java-docs ( http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html ),我可以使用对象引用。

Class methods cannot access instance variables or instance methods directly—they must use an object reference.

如果我更改 o4This 的属性会怎样? o4All 的属性也会被间接改变吗?

最佳答案

What if I change a property of o4This? Will the property of o4All also be changed indirectly?

,它会被改变。因为现在,o4Allo4This 都指的是同一个实例。您通过以下作业完成了此操作:-

Test.o4All = this.o4This;

在上面的赋值中,您不是在创建 o4This 引用的实例的副本,而是在 中复制 o4This 的值>o4All 引用。现在,由于 o4This 值是对某些 instance 的引用。因此,o4All 现在引用了与 o4This 相同的实例。因此,您使用引用对 instance 所做的任何更改也将反射(reflect)在其他引用中。

关于java - 将实例变量分配给静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14778120/

相关文章:

java - 回显 TextView 的内容?

Java-Stream,带有重复键的 toMap

java - 尝试调用从另一个类定义变量的方法时出现编译错误

Java - 链接堆栈实现,无法弄清楚为什么总是打印相同的数字

c++ - 在静态成员函数中访问非静态成员的解决方法

java.lang.ClassNotFoundException : org/apache/xerces/jaxp/DocumentBuilderFactoryImpl

java - Selenium 异常处理设计

java - Maven 项目中的多个 web.xml 数据库连接

java - 即使在应用程序关闭后,静态变量也会存在吗?

java - 在 javaFX 中使 Stage 静态。这是不是一个好主意?