Java Reference
In-Depth Information
Although shadowing is generally discouraged, one common idiom does involve shadowing.
Constructors often reuse a field name from their class as a parameter name to pass the value of the
named field. This idiom is not without risk, but most Java programmers have decided that the
stylistic benefits outweigh the risks:
class Belt {
private final int size;
public Belt(int size) { // Parameter shadows Belt.size
this.size = size;
}
}
Obscuring
A variable obscures a type with the same name if both are in scope: If the name is used where
variables and types are permitted, it refers to the variable. Similarly, a variable or a type can
obscure a package. Obscuring is the only kind of name reuse where the two names are in different
namespaces: variables, packages, methods, or types. If a type or a package is obscured, you cannot
refer to it by its simple name except in a context where the syntax allows only a name from its
namespace. Adhering to the naming conventions largely eliminates obscuring [JLS 6.3.2, 6.5]:
public class Obscure {
static String System; // Obscures type java.lang.System
public static void main(String[] args) {
// Next line won't compile: System refers to static field
System.out.println("hello, obscure world!");
}
}
 
 
Search WWH ::




Custom Search