在类或构造函数中使用 studentName 和 studentAverage 有何不同?
public class StackOverFlowQ {
String studentName;
int studentAverage;
public void StackOverFlowQ (String stedentName, int studentAverage){
}
}
在类或构造函数中使用 studentName 和 studentAverage 有何不同?
public class StackOverFlowQ {
String studentName;
int studentAverage;
public void StackOverFlowQ (String stedentName, int studentAverage){
}
}
它被称为阴影,并且有一个适用于这种情况的特定案例。
一个名为 n 的字段或形式参数的声明 d 在 d 的整个范围内隐藏了在 d 出现点的范围内的任何其他名为 n 的变量的声明。
为您提炼一点:
您已在构造函数中声明字段studentName
并studentAverage
作为形式参数。 在该构造函数的范围内,对上述两个名称的任何引用都将被视为使用参数,而不是其他更高级别的字段。
如果您需要引用该字段,请使用this
关键字,就像您取消引用该字段一样。
this.studentName = studentName;
this.studentAverage = studentAverage;
不仅在变量阴影的使用上存在巨大差异,在访问方面也存在巨大差异。在您的构造函数上,您将永远只有变量studentName
并且studentAverage
在它的范围内可用。实例化此类的人无法访问这些参数中的值,除非它们被捕获到字段中。
因此,名称相似的字段开始发挥作用。这些字段,取决于它们的可见性或通过其他方法暴露,实际上可以被其他类使用。
在构造函数中,如果您希望引用实例变量,则必须以this
;开头 否则你将引用参数。
例如:
public class StackOverFlowQ {
String studentName;
int studentAverage;
public StackOverFlowQ (String studentName, int studentAverage){
this.studentName = "Paul" // will point to the instance variable.
studentName = "Paul"; // will point to the parameter in the constructor
}
}