[英]Two constructors and static String variable
我有一个相当混乱的类,在其中我不理解为什么总是打印superUser
。 我知道,如果我要编写private String username = "user"
,那么我将能够在我的main
方法中调用它: System.out.println(o1.username)
。 在我的情况下,上面的代码也会打印出superUser,因为它是静态的。 但是我真的不明白。是因为Java会首先完全读取代码并意识到我有第二个对象o2
,它具有自己的构造函数,该函数将参数分配给局部变量username
?
我不明白的是为什么System.out.println(o1.getUsername());
打印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
}
}
您的username
是静态的。 这意味着,无论您拥有多少个PrintMe
实例,该变量永远只有一个实例。 变量username
在PrintMe
所有实例之间共享。 这意味着这里:
PrintMe o1 = new PrintMe();
PrintMe o2 = new PrintMe("superUser");
第二行将username
变量覆盖为superUser
。 由于在o1
或o2
上调用getUsername
返回相同的变量,因此您将获得superUser
作为输出。
要解决此问题,只需从变量声明中删除“ static
”一词:
private String username = "user";
由于username
是静态的,因此它不是实例( o1
, o2
)的属性,而是类的属性。 使用构造函数PrintMe(String)
,将修改静态username
。 因此,在创建o2
时, username
名将更改为“ superUser”。 如果在创建o2
之前打印o1.getUsername()
,将得到“用户”,然后得到“ superUser”。 删除username
的static
修饰符,您将获得预期的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.