【发布时间】:2015-04-21 13:58:54
【问题描述】:
在下面的代码中我有this.name= name,当我打印出来时,我得到了学生的名字。
但是,当我更改 name= this.name 的代码时,我在打印输出中收到 null,这是为什么呢?
或者当我进一步更改name = name。
public Student(String name, String groupName, int javaProf, String cprNumber, Gender gender) {
this.name=name;
//"name" refers to method parameter and "this.name" refers to the instance variable. Instance field
//takes precedence over method parameter and avoids name clash
this.groupName = groupName;
this.javaProf = javaProf;
this.cprNumber = cprNumber;
this.gender = gender;
this.courses = new HashMap<>();
}
}
【问题讨论】:
-
您的问题的答案隐藏在代码sn-p的注释中。 :)
-
因为
this指的是你的实例变量。 -
如果把代码改成
name = this.name,就是把参数值设置为字段值,默认为null。你为什么要这么做? -
@Jon Skeet 这是一个练习中的一个问题,可以更好地理解参数和实例变量的概念,谢谢大家的回复。
标签: java variables methods instance