gpt4 book ai didi

java - 从实例化对象调用主类中的方法

转载 作者:行者123 更新时间:2023-12-01 11:19:54 25 4
gpt4 key购买 nike

我想做的是:

public class MainClass {
private UIController uIController;

MainClass() {
uIController = new UIController();
}

public void MethodIWantToCall() {
//Do Something
}
}

UIController 类示例:

public class UIController {
UIController() {
//Call a method in MainClass here, for example MethodIWantToCall()
}

public void MethodA {
//Call a method in MainClass here, for example MethodIWantToCall()
}
}

我想要做的是,当用户与 UI 交互时,UIController 传递给 MainClass 命令,调用其方法或将值返回给 MainClass。

最佳答案

您需要将 MainClass 实例的引用传递给 UIController 实例,例如:

public class UIController {
private final MainClass mainClass;
UIController (final MainClass mainClass) {
this.mainClass = mainClass;
//Call a method in MainClass here, for example MethodIWantToCall()
this.mainClass.MethodIWantToCall();
}

public void MethodA() {
//Call a method in MainClass here, for example MethodIWantToCall()
this.mainClass.MethodIWantToCall();
}
}

然后

uIController = new UIController(this);

PS:Java中的方法应该以小写开头。

关于java - 从实例化对象调用主类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31371324/

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