Resources‎ > ‎Java Basics‎ > ‎

Scope

Scope refers to the area of a program where a variable can be referenced. 
  • Data members of a class may be referenced from anywhere in the class. 
  • Parameters of a method may be referenced only within the method.
  • Local variables declared in a method may be referenced only within the method.
public class Name {

    private String first;
    private String last;

    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }

    public String getFirst() {
        return this.first;
    }

    public String getLast() {
        return this.last;
    }

    public void printFullName() {
        //the local variable full can
        //only be referenced in the
        //printFullName method                                              

        String full = first + " " + last;
        System.out.println(full);
    }

    public boolean equals(Name toCompare) {
        //the parameter toCompare can
        //only be referenced in the
        //equals method                                                     

        return (this.first.equals(toCompare.getFirst()) && this.last.equals(toCompare.getLast()));
    }

}



this

The Name class above also shows an example of using the this reference.  Notice that the Name constructor names its parameters first and last, but the class Name already has data members first and last.  In this case, there is a naming conflict in the constructor.  One way to solve the conflict would be to choose different names for the parameters (e.g., newFirst and newLast).  The more common practice, however, is to explicitly refer to the instance fields using thisthis.first = first indicates that the first variable of this object should get the value of the variable first that is local to the method.
Comments