(^342) | Inheritance, Polymorphism, and Scope
int param = 0; // Instance member param
public intsomeMethod(int param) // Defines local param
{
int var; // Defines local var
// Define and set local CONST to instance CONST 2
final intCONST = this.CONST2;
if (param > this.param) // Compare local and instance params
var = param CONST; // Use local values
else
var = this.param this.CONST; // Use instance values
returnvar;
}
}
Understanding the internal scope rules helps to avoid or locate errors in implementing
the internal representation of the class. An example of a scope-related error is when you de-
clare a local identifier that shadows a class member, but misspell the name in the local dec-
laration. The compiler won’t complain, but merely directs all of the references to the local
identifier to its correctly spelled class member equivalent, as shown here:
public classSomeClass
{
static intvar; // Class member var
public static voidsomeMethod(int param)
{
int ver; // Misspelling of var
var = param * param; // Accidentally refers to class member var
System.out.println("" + var); // Accidentally refers to class member var
System.out.println("" + SomeClass.var); // Intentional reference to class member var
}
}
This program exhibits erroneous behavior in which a class member is changed and dis-
played as a side effect of calling a method. Knowing the scope rules leads us to look for ref-
erences to the class member within the method, and then to check the local declarations.
The last line of someMethodillustrates how to intentionally access a shadowed class field. We
just use the class name to refer to the field.
External Scope
The external access scope rules for members control their use by code that is outside of the
class. Java allows class members to be accessed from three external places: derived classes,
members of the same package, and code external to the package.
A package contains a set of related classes, and sometimes we want to make members
of those classes accessible to each other, even if they aren’tpublic. For example, suppose
that aDateclass is part of acalendarpackage. Another class, calledShowWeek, in the package