-3

I have a class with a constructor

public class Test {
  private static String name;

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

  public static String getName() {
    return this.name;
  }
}

Here I've created 2 instances of the constructor and used System.out.println() to output the "getName()" function from both instances in the terminal

Test test = new Test("Tom");
Test test1 = new Test("Kenny");

System.out.println(test.getName());
System.out.println(test2.getName());

output:

Tom
Tom

Both of the outputs we're "Tom", how would I make it to where test.getName() outputs "Tom" and test2.getName() outputs "Kenny

I've looked for answers on StackOverFlow, google, etc and can't find anything so help would be very much appreciated

1 Answers1

1

Your field is static, meaning that all objects you create for this class share the same value.

private static String name -> private String name

For non-static fields every object has it's own value.

TomekK
  • 403
  • 1
  • 4
  • 11