如何从另一个 class [JAVA] 访问同一个对象

How to access the same object from another class [JAVA]

我正在管理一个 GUI,我想知道是否有任何方法可以从另一个 class 管理一个 class 中实例化的 GUI。我解释得更好: 一个 class 创建了 GUI 对象,有没有办法修改另一个 class 的相同 GUI 对象? 即使我将对象创建为 public,我也无法在不收到错误 "cannot make a static reference to the non-static field" 的情况下访问它 我被这个问题困住了,因为在 java 中没有 C-Style 全局变量... 如果不可能,我如何创建一个智能管理的 GUI 系统? 如果我在一个 class 中创建 GUI,我以后如何修改它,因为在其他 classes 中发生了什么?

您可以采用多种方式。例如 -

  1. 将class1的reference传递给class2的实例。
  2. Singleton 您可以创建的对象,该对象在整个应用程序中始终相同。

我认为你可以使用单例 class 作为 GUI。

public class GUI {
private static GUI ourInstance = new GUI();

public static GUI getInstance() {
    return ourInstance;
}

private GUI() {
    //private constructor
}
public void method() {}
}

然后你就可以到处使用了。 单例 class 意味着只有一个对象会在你的记忆中。

GUI.getInstance().method();