Monday, January 7, 2013

Java Best Practices to Follow while Overloading Method and Constructor

Method overloading in Java needs to be use carefully. Poorly overloaded method add not only add confusions among developers who use that but also they are error prone and leaves your program on compiler's mercy to select proper method. It's best to avoid issues related to method overloading in Java by following some Java best practices. For those who doesn’t know What is method overloading in Java, method overloading means declaring two method with same name but different method signatures. This is generally done to create method which operates on different data types e.g. System.out.println() which is overloaded to accept different types of parameters like String, double, int etc, see this Java tutorial on method overloading and static vs dynamic binding for more details. By the way all of these Java best practices which are explained in context of method overloading are equally applicable to constructor overloading in Java, because in terms of overloading method and constructors are almost same.

Java Best Practices -  Method Overloading

Java best practices for method and constructor overloading in JavaHere are some of the common things which you can remember while overloading method or constructor in Java. These Java best practices are completely based upon experience and you may have some more to add on this list. let’s see my list of Java best practices while overloading method in Java.

1) Don't overload method which accept same number of parameter with similar types
Two overloaded method which accept same number of argument with similar types i.e. which follow same type hierarchy is most common mistake while overloading method  in Java. For example, find out which version of overloaded method will be invoked in following scenario :

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

 * Java program to demonstrate some best practice to following while overloading
 * method in Java.This Java program shows a case of confusing method overloading in Java
 * @author Javin Paul

public class OverloadingTest {
    public static void main(String args[]){
       List abc = new ArrayList();
       List bcd = new LinkedList();
       ConfusingOverloading co = new ConfusingOverloading();
       co.hasDuplicates(abc); //should call to ArryList overloaded method
       co.hasDuplicates(bcd); //should call to LinkedList overloaded method


class ConfusingOverloading{
    public boolean hasDuplicates (List collection){
        System.out.println("overloaded method with Type List ");
        return true;
    public boolean hasDuplicates (ArrayList collection){
        System.out.println("overloaded method with Type ArrayList ");
        return true;
    public boolean hasDuplicates (LinkedList collection){
        System.out.println("overloaded method with Type LinkedList ");
        return true;

overloaded method with Type List
overloaded method with Type List

To surprise of some programmers method with argument type List is called both the time, instead of expected method which takes ArrayList and LinkedList, because method overloading is resolved at compile time using static binding in Java. This is  also one of the reason, why its important to clearly understand difference between method overloading and overriding in Java. Here expected case is result of mistaking overloading as overriding, which work on actual object and happens at runtime. To know more about static and dynamic binding in Java , you can also see my post difference between static and dynamic binding in Java.

2) Use radically different types while overloading method in Java
It's completely legal and there is no ambiguity when two overloaded method accepts radically different types like String and Integer. Though both overloaded method will accept only one parameter, it’s still clear which method is called because both types are completely different to each other. Both programmer and compiler both know which method will be invoked for a particular call. One of the example of this kind of overloading is constructor of java.util.Scanner class which accepts File, InputStream or String as parameter, as shown below :

Scanner(File source)
Scanner(InputStream source)
Scanner(String source)

3) Beware of Autoboxing while overloading method in Java
Prior to introduction of Autoboxing and unboxing in Java 5, method which accept primitive type and object type were radically different and it’s clear which method will be invoked. Now with autoboxing it's really confusing. Clasical example of this kind overloading mistake is ArrayList’s  remove() method, which is overloaded to accept index as well as Object. when you store Integer in ArrayList and call remove() method, It’s hard to find out which remove() method will be called, as shown in below example :

List<Integer> numbers = new ArrayList<Integer>();
System.out.println("numbers: " + numbers);
numbers.remove(1); //should remove "1" as element or 2nd element from ArrayList
System.out.println("numbers: " + numbers);

numbers: [1, 2, 3]
numbers: [1, 3]

Many Java programmer expect that Integer(1) object would  be removed but since remove() is overloaded, compiler choose remove(int) over remove(Object). Rules of which overloaded method gets chosen in case of autoboxing is complex and hard to remember, so Its best to avoid two overloaded method where one accept Object and other accept primitive type. If by any chance you must have to do this then make sure both of them perform identical function.

Other Java best practices articles from Javarevisited Blog


Steve said...

I like this kind of advice which is based on experience. Though You don't call all these as Java best practices, rather common mistakes to avoid while doing method overloading and constructor overloading in Java.

James said...

One more to add in your list of best practices. Suppose If you like to overload methods so that it will work for every type in Java than you need to overload it for primitive type
and Object.

All most all API including JDK does that. Look at Arrays.toString() method it has overloaded for all above types.

Maulik Patel said...

thanks dude, for giving such a great information. but i want to know, why method overloading called compile time polymorphism?

Post a Comment