繁体   English   中英

类中的实例变量或在Java中的构造函数中将它们用作参数之间有什么区别?

[英]What is the difference between instance variables in a class or using them as parameters in a constructor in Java?

在类或构造函数中使用studentName和studentAverage有何不同?

public class StackOverFlowQ {

    String studentName;
    int studentAverage;


    public void StackOverFlowQ (String stedentName, int studentAverage){

    }
}

这称为阴影 ,在这种情况下有一个特定的情况。

在整个d范围内,名为n的字段或形式参数的声明d在整个d范围内,在d发生时在范围内的任何其他名为n的变量的声明。

为您提炼一下:

您已声明的字段studentNamestudentAverage在你的构造形式参数。 在该构造函数的范围内,对以上两个名称的任何引用将被视为使用参数,而不使用其他更高级别的字段。

如果您需要引用该字段,则使用this关键字,就像您要取消引用该字段一样。

this.studentName = studentName;
this.studentAverage = studentAverage;

用法不仅在可变阴影方面而且在访问方面都存在巨大差异。 在你的构造函数,你将只拥有变量studentNamestudentAverage它的范围内可用。 实例化该类的人员无法访问那些参数中的值,除非将它们捕获到字段中。

因此,类似命名的字段开始起作用。 这些字段取决于它们的可见性或通过其他方法的暴露程度,实际上可以由其他类使用。

在构造函数中,如果要引用实例变量,则必须以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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM