20.5 Overloading Generic Methods

A generic method may be overloaded. Each overloaded method must have a unique signature (as discussed in Chapter 7). A class can provide two or more generic methods with the same name but different method parameters. For example, we could provide a second version of generic method DisplayArray (Fig. 20.3) with the additional parameters low-Index and highIndex that specify the portion of the array to output (see Exercise 20.8).

A generic method can be overloaded by nongeneric methods with the same method name. When the compiler encounters a method call, it searches for the method declaration that best matches the method name and the argument types specified in the call. For example, generic method DisplayArray of Fig. 20.3 could be overloaded with a version specific to strings that outputs the strings in tabular format (see Exercise 20.9)—the non-generic version of a method takes precedence over a generic version. If the compiler cannot match a method call to either a nongeneric method or a generic method, or if there’s ambiguity due to multiple possible matches, the compiler generates an error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset