
将值从一个类传递到另一个类的方法
在java中,当需要在不同的类之间传递值时,有几种方法可以实现。其中一个常见的挑战是在不重新实例化主类的情况下,将值传递回主类。
一种有效的方法是使用返回方法。被调用的类(即a类)可以编写一个返回方法来返回所需的 index 值。然后,主类可以通过调用该方法来检索 index 值。
另一种方法是使用回调函数。回调函数是一个传递给另一个类的函数指针。当操作完成时,被调用的类将调用回调函数,将 index 值传递回主类。
立即学习“Java免费学习笔记(深入)”;
示例代码:
在主类(r)中:
public class r {
public void indexcallback(int index) {
// 使用 index 值实现定位功能
}
}在a类(tihuan)中:
public class tihuan {
private r r;
public tihuan(r r, string listx) {
this.r = r;
}
public int find() {
// 查找字符并获取 index
// ...
// 调用回调函数传递 index 值
r.indexcallback(index);
}
}在主类中使用:
Tihuan find = new Tihuan(this, youInput); find.find();
通过使用回调函数,可以在不重新实例化主类的情况下将 index 值传递回主类,从而实现定位功能。










