Java Reference
In-Depth Information
Method overloading
If your method needs to be accessed by any other method which has need to compute same
thing with different data types then you may need to define several methods with same name
but with parameters having different data types. Method overloading can be used in cases
where the same class is used to perform many tasks. Suppose you have created a class to
draw various shapes. Then you can use method overloading like this:
public class shapes {
public void draw(String s[]){
}
public void draw(int i){
}
public void draw(float f){
}
public void draw(int i, float f){
}
}
You can see that even though method names are the same but the method signatures are dif-
ferent. The benefit is that we are creating just one method and by passing different paramet-
ers we are able to perform many types of computations. Otherwise we would have ended up
defining many methods with different names; each method for performing a different com-
putation. Maintaining many different methods with different method names is a time con-
suming task. In contrast, many methods with the same name saves time.
The drawback of method overloading is that it can result in errors. Generally for better pro-
gramming practices each entity whether it is a variable or a method; the naming of the entity
should be descriptive so that we know what it is supposed to do in programming. When us-
ing a single method name for doing various computations, we are sacrificing this clarity in
code.
Search WWH ::




Custom Search