1.9.4 Name and Method Overloading
Keywords: current

Next: 1.10 The Visitor Pattern Up: 1.9 Loose Ends Previous: 1.9.3 Exceptions as Errors

##
1.9.4 Name and Method Overloading

In Java, the same name can simultaneously be used for a local variable or method parameter, different fields of the same object, and different methods of the same object. Java uses context and type information to determine the meaning of a name. For example, many Java programmers would write the constructor for the class `Cons` above as follows:

      Cons(Object first, List rest) {
        this.first = first;
        this.rest = rest;
        }

In this example, the names `first` and `rest` each have two different meanings. Java resolves potentially ambiguous uses of names by using the innermost (most local) definition of the name. Hence, the prefix `this.` is required to distinguish the `first` and `rest` fields of `this` from the constructor parameters of the same name.

While the use of the same name for different kinds of program entities is widely accepted as good programming practice, the use of one name for several different fields or methods is more controversial. A Java subclass B can introduce a field with exactly the same name n as a field in its superclass A. The inherited field is not overridden (what would overriding mean in this context?); it is merely ``shadowed''. When the name n appears in a method of B, its meaning depends on the type of the receiver. If the receiver is `this`, then the new field n introduced in B is meant. But if the receiver has type A rather than B, then the old field n introduced in A is meant. Warning: duplicate field names can be the source of insidious program errors that are very difficult to diagnose. For this reason, we strongly recommend against using them.

Duplicate method names are less controversial but can still be dangerous. In a class, Java permits the same method name to be used for different methods as long as their argument lists do not identical the same length and same types. The practice of defining more than one method in a class with same name is called method overloading. Java resolves overloaded method names using the types of the argument expressions. When the Java compiler encounters a method invocation involving an overloaded method, it determines the types of the method arguments and uses this information to select the ``best'' (most specific) match from among the alternatives. If no best method exists, the program is ill-formed and will be rejected by the Java compiler.

We urge restraint in using the same name for different methods involving the same number of arguments. Since static type information is used to resolve which method is meant, program errors may be difficult to find because the programmer may not infer the correct static type when reading the code.

Next: 1.10 The Visitor Pattern Up: 1.9 Loose Ends Previous: 1.9.3 Exceptions as Errors