Friday, June 26, 2009

Method Overloading

Defining two or more methods with the same name in a class is called method overloading. The name of a method together with the types and sequence of the parameters form the signature of the method, the signature of each method in a class must be distinct to allow the compiler to determine exactly which method you are calling at any particular point. The return type has no effect on the signature of a method. You cannot differentiate between two methods just by the return type. This is because the return type is not necessarily apparent when you call a method. You can see an example in the following code :

class TryMethodOverloading {

    public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }


    public static String valueOf(int i) {
        return Integer.toString(i, 10);
    }

}


Constructors are methods that can be overloaded, just like any other method in a class. In most situations, you will want to generate objects of a class from different sets of initial defining data, I modified the classes from "our first project" to demonstrate it. Click here to download the updated classes.

No comments:

Post a Comment