简体   繁体   中英

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

How is using studentName and studentAverage different in the class or in the constructor?

public class StackOverFlowQ {

    String studentName;
    int studentAverage;


    public void StackOverFlowQ (String stedentName, int studentAverage){

    }
}

It's called shadowing , and there's a specific case that applies to this situation.

A declaration d of a field or formal parameter named n shadows, throughout the scope of d, the declarations of any other variables named n that are in scope at the point where d occurs.

To distill that a bit for you:

You have declared fields studentName and studentAverage as formal parameters in your constructor. In the scope of that constructor , any references to the above two names will be treated as using the parameters, and no other higher level field.

If you need to refer to the field, then use the this keyword as if you were dereferencing the field.

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

There's a huge difference in usage not just in variable shadowing, but access as well. On your constructor, you will only ever have the variables studentName and studentAverage available within the scope of it. Someone that instantiates this class can't access the values in those parameters unless they're captured into fields.

Hence, the fields which are similarly named come into play. Those fields, depending on their visibility or exposure through other methods, can actually be used by other classes.

In the constructor, if you wish to reference the instance variables you must preface with this ; otherwise you will be referencing the parameters.

For example:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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