0

My goal is to return a value from local variable that I need to set first by calling a method. It could sound dumb, sorry, I do not have much practice with java yet, tried googling for 2 hours and haven't found the solution.

Step by step goal:

  1. Create local String variable in constructor
  2. Set its value
  3. Create method that will return this value

This is what I got yet:

public class TestString{

    public TestString(){

    }

    public String name;

    public TestString (String name){
        this.name=name;
    }

    public String toString() {
        return this.name;
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    naming conventions aside, what is not working? – rick Mar 11 '19 at 11:24
  • OK, what is the problem with what you have? The empty constructor is not necessary, but other than that? – RealSkeptic Mar 11 '19 at 11:24
  • Can you tell me what is expected? the toString method seems to do the job. If you want to prevent instantiating TestString without a string, then remove the default constructor. – Sid Mar 11 '19 at 11:24
  • your option is 100% correct. You can also call the default constructor (no need to create one), and implement a "setName(String name)" method. – aran Mar 11 '19 at 11:25
  • I'm not sure if I wrote the right code :D – KevinMarkus Mar 11 '19 at 11:26
  • 2
    One thing, though. This variable is an **instance** variable. It's not a local variable. There is no way to access a local variable from outside the scope where it is created. – RealSkeptic Mar 11 '19 at 11:26

1 Answers1

0

It is called a POJO: read further here

public class TestString {

private String name;

public TestString(String name) {
    super();
    this.name = name;
}

public TestString() {
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "TestString [name=" + name + "]";
}

}

your Goals

Step by step goal:

  1. Pass a String variable in a constructor

    TestString testString = new TestString("this is a test string");

  2. Set its value (not from the constructor) - setters

    testString.setName("this is a new test string");

  3. return variable value - getters

    String res = testString.getName();

Van_Cleff
  • 842
  • 6
  • 14