简体   繁体   中英

How to give a variable value through another method in another class in Java

Simply put here is what I am trying to do:

class Main { 
    public static void main (String[] args) {
        List option = new List();
        SetGet call = new SetGet();
        option.names();
        call.getName();
    }
}

class List {
    public void names() {
        SetGet tell = new SetGet();
        tell.setName("Frank");
    }
}

class SetGet() {
    private String info;

    String getName() {
        return info;
    }

    public void setName(String name) {
        info = name;
    }
} 

Essentially I have a main method that will tell another method from another class to set the name of something. Yet whenever I request getName from the main method, it always comes back null even though I already set a name for it. This is a really simplified version of what I am trying to do. Any assistance is greatly appreciated.

When you call option.names(); in your main method, it creates a new SetGet object named tell and sets its name to "Frank".

After that you call call.getName(); on a newly created SetGet named call .

Both the SetGet objects are not related, they are different.

You creating 2 different objects of SetGet. You can try to return the object tell and overwrite call with the returned object.

class Main {
  public static void main (String[] args) {
    List option = new List();
    SetGet call =  new SetGet();
    call = option.names();
    System.out.println(call.getName());
  }
}

class List {
  public SetGet names() {
    SetGet tell = new SetGet();
    tell.setName("Frank");
    return tell;
  }
}

class SetGet {
  private String info;

  String getName() {
    return info;
  }

  public void setName(String name) {
    info = name;
  }
}

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