| Suppose that you create a class that includes a method with an 
              integer argument:    void 
              A_method (int k) {...} You decide later that you need a method that accomplishes the same 
              task but it requires a float 
              argument. In some procedural languages, you would create a new method 
              with a slightly different name:    void 
              A_method_f (float x) {...} A more elegant solution would allow you to use exactly the same 
              name for the new method and the compiler would determine by 
              the argument type which method to use.     void 
              A_method (int k) {...}    void 
              A_method (float x) {...} In OOP this is allowed (and encouraged) and is called overloading. 
              For example, we have used the static method    System.out.println 
              (String)  to print messages to the Java console. This is actually just one 
              of several println(...) 
              methods in the PrintStream 
              class, an instance of which the static variable 
              System.out references. The other overloaded 
              versions of println() 
              include:  
             println 
              () <- prints out a line separator  println (boolean)
 println (char)
 println (char[])
 println (double)
 println (float)
 println (int)
 println (long)
 println (java.lang.Object)
 
 Overloaded methods with the same argument list must all have the 
              same return type. Otherwise, either the number of arguments or the 
              type of arguments must differ among the overloaded methods. We saw in the previously the example of overloading 
              of constructors. This allows the option of creating a class 
              with alternative initializations. The discussion of this(), 
              super() in Chapter 4 will return to the case of 
              overloaded constructors. Latest update: Oct. 16, 2004 |