Overloading Explanation

Overloading methods

Overloading is a one of the ways in which Java implements one of the key concepts of Object orientation, polymorphism. Polymorphism is a ten guinea made up word that is constructed from Ply meaning "many" and "morphism" implying meaning. Thus a overloading allows the same method name to have multiple meanings or uses. Overloading of methods is a compiler trick to allow you to use the same name to perform different actions depending on parameters. It takes advantage of the fact that Java resolves the actual method that gets called at runtime rather than compile time.
Thus imagine you were designing the interface for a system to run mock Java certification exams (who could this be?). An answer may come in as an integer, a boolean or a text string. You could create a version of the method for each parameter type and give it a matching name thus
markanswerboolean(boolean answer){ 
        } 

markanswerint(int answer){ 
        }

markanswerString(String answer){ 
        }
This would work but it means that future users of your classes have to be aware of more method names than is strictly necessary. It would be more useful if you could use a single method name and the compiler would resolve what actual code to call according to the type and number of parameters in the call.

There are no keywords to remember in order to overload methods, you just create multiple methods with the same name but different numbers and or types of parameters. The names of the parameters are not important but the number and types must be different. Thus the following is an example of an overloaded markanswer method
void markanswer(String answer){ 
        } 

void markanswer(int answer){ 
        }
The following is not an example of overloading and will cause a compile time error indicating a duplicate method declaration.
void markanswer(String answer){ 
        }

void markanswer(String title){ 
        }
The return type does not form part of the signature for the purpose of overloading. 
Thus changing one of the above to have an int return value will still result in a compile time error, but this time indicating that a method cannot be redefined with a different return type. 
Overloaded methods do not have any restrictions on what exceptions can be thrown. That is something to worry about with overriding.

Overloaded methods are differentiated only on the number, type and order of parameters, not on the return type of the method

Comments

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams