1:public class GamePlayer {
2: public static String playername;
3: public GamePlayer(String name) {
4: playername = name;
5: }
6: public String toString() {
7: return "[player:" + playername + "]";
8: }
9: public static void main(String[] args) {
10: GamePlayer[] player = new GamePlayer[3];
11: player[0] = new GamePlayer("Mad Hatter");
12: player[1] = new GamePlayer("March Hare");
13: player[2] = new GamePlayer("Alice");
14: for (int i = 0; i < player.length; i++) {
15: System.out.println(player[i]);
16: }
17: }
18:}
期望输出结果:
[player:Mad Hatter]
[player:March Hare]
[player:Alice]
实际输出结果:
[player:Alice]
[player:Alice]
[player:Alice]
错在哪?
參考答案:错在这里:
2: public static String playername;
把static去掉,static指的是静态变量,也就是类变量,是所有同类型对象公用的,
public class UserData{
private static int Counts=0;
public UserData(){
this.Counts++;
}
public static int getCounts(){
return Counts;
}
public static void main(String[] args){
UserData t1=new UserData();
System.out.println(t1.getCounts());
UserData t2=new UserData();
System.out.println(UserData.getCounts());
}
}