I have a rather confusing class, in which I don't understand why superUser
is always being printed. I know that if I would have written private String username = "user"
, then I would have been able to call it in my main
method like that: System.out.println(o1.username)
. In my case the above would also print out superUser, because it is static. But I don't really get it.. is it because Java reads the code completely first and realizes that I have a second object o2
, which has its own constructor, where the argument is assigned to the local variable username
?
What I don't get is why System.out.println(o1.getUsername());
prints superUser.
public class PrintMe {
private static String username = "user";
private int password = 1234;
public PrintMe(){}
public PrintMe(String username){
PrintMe.username = username;
this.password = 5678;
}
public void changePassword(int password){
System.out.println("The old password of " + this.getUsername() +
" was " + this.password);
this.password = password;
}
public String getUsername(){
return PrintMe.username;
}
public static void main(String[] args){
PrintMe o1 = new PrintMe();
PrintMe o2 = new PrintMe("superUser");
System.out.println(o1.getUsername()); // superUser
System.out.println(o1.password); // 1234
System.out.println(o2.getUsername()); // superUser
System.out.println(o2.password); // 5678
o1.changePassword(9000); // The old password of superUser was 1234
System.out.println(o1.getUsername()); // superUser
System.out.println(o1.password); // 9000
System.out.println(o2.getUsername()); // superUser
System.out.println(o2.password); // 5678
}
}