简体   繁体   中英

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.

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:

public Final(){
Setter t = getResultado();
    System.out.println(t);

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

initialize the object:

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

then call the method through your instance of 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM