从一个班级到另一个班级的对象?

时间:2021-07-27 20:14:31

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);

1 个解决方案

#1


0  

Problem is very simple: You never initialize an instance of your Setter class. You create a reference/pointer to a Setter object, but its null and you are trying to call a method contained in this class. So, you should probably be getting a NullPointerException. The fix to this is simple, just

问题很简单:你永远不会初始化你的Setter类的实例。您创建一个指向Setter对象的引用/指针,但它的null并且您正在尝试调用此类中包含的方法。所以,你应该得到一个NullPointerException。对此的修复很简单,只是

initialize the object:

初始化对象:

Setter t = new Setter("my string");

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对象。

#1


0  

Problem is very simple: You never initialize an instance of your Setter class. You create a reference/pointer to a Setter object, but its null and you are trying to call a method contained in this class. So, you should probably be getting a NullPointerException. The fix to this is simple, just

问题很简单:你永远不会初始化你的Setter类的实例。您创建一个指向Setter对象的引用/指针,但它的null并且您正在尝试调用此类中包含的方法。所以,你应该得到一个NullPointerException。对此的修复很简单,只是

initialize the object:

初始化对象:

Setter t = new Setter("my string");

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对象。