[英]Gettin an object from one class to another?
Need to bring the information from one class to the other, I need the final value of fin to return in getResultado.需要将信息从一个类带到另一个类,我需要在 getResultado 中返回 fin 的最终值。
public class Setter {
String fin = "";
public Setter(String result){
fin = result;
}
public String getResultado(String inicio){
return fin;
}
}
Here is the other class where I need to implement fin:这是我需要实现 fin 的另一个类:
public Final(){
Setter t = getResultado();
System.out.println(t);
Problem is very simple: You never initialize an instance of your Setter
class.问题很简单:你永远不会初始化你的
Setter
类的实例。 You create a reference/pointer to a Setter
object, but its null
and you are trying to call a method contained in this class.您创建了一个指向
Setter
对象的引用/指针,但它为null
并且您正在尝试调用此类中包含的方法。 So, you should probably be getting a NullPointerException
.所以,你可能应该得到一个
NullPointerException
。 The fix to this is simple, just解决这个问题很简单,只需
initialize the object:初始化对象:
Setter t = new Setter("my string");
then call the method through your instance of Setter:然后通过您的 Setter 实例调用该方法:
t.getResultado();
Edit: If you don't want to give the variable fin
a value when you create an object Setter
, just add a second constructor right underneath the first one like this:编辑:如果您不想在创建对象
Setter
时给变量fin
一个值,只需在第一个构造函数下方添加第二个构造函数,如下所示:
public Setter() {
//do whatever, maybe call the getResultado() method right here?
}
It will allow you to create Setter objects without any parameters or changing value of the variable.它将允许您创建没有任何参数或更改变量值的 Setter 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.