gpt4 book ai didi

java - 相同(?)对象的不同对象引用

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:37 26 4
gpt4 key购买 nike

我最近问过关于从另一个类获取类的唯一实例的问题。

( How to get specific instance of class from another class in Java? )

所以,我正在努力让它发挥作用:

我的申请:

public class Application
{

// I will always have only one instance of Application

private static Application _application;

// Every instance of Application (one in my case) should have its own View

private View view;

// Constructor for new instance of Application

private Application()
{
view = new View();
}

// Getter for my unique instance of Application

public static Application getSharedApplication()
{
if (_application == null)
_application = new Application();
return _application;
}

// Main class

public static void main(String[] args)
{
// So I'm accessing my instance of Application
Application application1 = getSharedApplication();

// Here is object reference
System.out.println(application1);

// And now I'm accessing the same instance of Application through instance of View
Application application2 = application1.view.getApplication();

// Here is object reference
System.out.println(application2);
}

}

我的 View :

public class View
{

// I'm accessing my instance of Application again

public static Application application = Application.getSharedApplication();

// This method should return my unique instance of Application

public Application getApplication()
{
return application;
}

}

问题是 main 方法返回不同的对象引用。

Application@1430b5c
Application@c2a132

我的代码有什么问题?

最佳答案

这是发生了什么:

  • 程序首先调用Application application1 = getSharedApplication();
  • 然后调用调用 new Application() 的静态方法 - 该调用需要加载 View 类,它是 Application 的成员。
  • View 类已加载,其静态成员已初始化并运行 getSharedApplication();(请注意,在此阶段,_application 仍为 null)。这也创建了一个 new Application()

您现在有 2 个应用程序实例。

请注意,如果您将 View v = new View(); 添加为 main 的第一行,您只有一个 Application 实例(从 View 的静态变量加载一次) .当您认真思考但不是很直观时,这是有道理的...

关于java - 相同(?)对象的不同对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992796/

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