在类或构造函数中使用studentName和studentAverage有何不同?
public class StackOverFlowQ {
String studentName;
int studentAverage;
public void StackOverFlowQ (String stedentName, int studentAverage){
}
}
最佳答案
它称为shadowing,在这种情况下有一个特定的情况。
在整个d范围内,名为n的字段或形式参数的声明d在整个d范围内,在d发生时在范围内的任何其他名为n的变量的声明。
为您提炼一下:
您已经在构造函数中将字段studentName
和studentAverage
声明为形式参数。在该构造函数的范围内,对以上两个名称的任何引用将被视为使用参数,而不使用其他更高级别的字段。
如果需要引用该字段,请使用this
关键字,就像您要取消引用该字段一样。
this.studentName = studentName;
this.studentAverage = studentAverage;
用法不仅在可变阴影方面而且在访问方面都存在巨大差异。在构造函数上,您将只能在其范围内使用变量
studentName
和studentAverage
。实例化该类的人员无法访问那些参数中的值,除非将它们捕获到字段中。因此,类似命名的字段开始起作用。这些字段取决于它们的可见性或通过其他方法的暴露程度,实际上可以由其他类使用。
关于java - 类中的实例变量或在Java中的构造函数中将它们用作参数之间有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29265873/