In short your "getter" is returning what the variable value you are giving it -> string(type) variable name = "unassigned". You will always tell it to set the variable named "name" to the String unassigned. try this
public void setName(String name) {
this.name = name;
}
Additionally you would want to create a constructor and make it overall more efficient (constructors can get rid of the setters and what not).
In full:
public class Main {
public static void main(String[] args){
Program3a testClass = new Program3a();
testClass.setName("Rex");
System.out.println(testClass.getName());
}
}
public class Program3a {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Or the better looking constructor
public Program3a(String name) {
this.name = name;
}
this will require you to update your tester class of course (I use main).
Program3a testClass = new Program3a("Rex");
System.out.println(testClass.getName());
Constructors are automatically created as a ghost. This being overridden can take in the parameters of variables and reduce un-needed coding. Once this is created you use line Program3a testClass = new Program3a("Rex");
to create a new class. The Rex now auto fills the variable Named and continues to use this value when testClass.getName()
is called until altered.