gpt4 book ai didi

java - 如何使类的实例在不同的方法中可用?

转载 作者:行者123 更新时间:2023-12-01 10:19:59 27 4
gpt4 key购买 nike

我已经在方法 (private void jButton2ActionPerformed) 中创建了类 DownloadManager 的实例,并且需要在另一个方法中访问它?

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//need to access the instance dman here
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DownloadManager dman = new DownloadManager();
dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
dman.setVisible(true);
}

最佳答案

"If you want to be able to access a variable from two different methods, define the variable in the enclosing scope of the method." -Sweeper

这基本上意味着您应该将变量“拖动”到方法之外:

DownloadManager dman = new DownloadManager(); //Should put the variable here!
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//need to access the instance dman here
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//DownloadManager dman = new DownloadManager(); I moved this line to above!
dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip");
dman.setVisible(true);
}

这很简单不是吗?

或者,您可以创建一个类来获取下载管理器:

public final class DownloadManagerUtility {
private DownloadManagerUtility () { // private constructor so that people don't accidentally instantiate this

}

private DownloadManager dman = new DownloadManager();
public static void getDownloadManager() { return dman; }
}

这样做的好处是您可以在单独的类中添加更多与下载管理器相关的方法,从而提高可维护性。

关于java - 如何使类的实例在不同的方法中可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35659052/

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