Why Return Type Cannot Distinguish Overloaded Methods

Overview

This post briefly answer the question of why return type cannot distinguish overloaded methods and demonstrated codes are given too.

Why Return Type Cannot Distinguish Overloaded Methods

When I was leaning the overloaded methods, I have a question: can return type be used to distinguish overloaded methods? The answer is no and the following is the explanation:

More specifically, the question here is, is it OK to write say, int foo(int i); and char foo(int i); are these two are considered as overloaded method and be used in programs? The answer is no, you cannot use the return type to distinguish overloaded methods, it is because methods could be called without using the return values, this means, it is OK to write it as for(4), then how does the compiler could be able to distinguish them, it is demonstrated by the following code:

public class Tester {
    public static void main(String[] args) {
        OverloadMethod testMethods = new OverloadMethod();
        char ch = testMethods.foo(0);
        System.out.println(ch);
        System.out.println("Hell Java!");
    }
}

class OverloadMethod {
   public int  foo(int i) {return 0;}
   public char foo(int i) {return 'c';} // compiler error: foo(int) is already defined in OverloadMethod
}

Summary

In this post, I discussed and explained why return type cannot distinguish overloaded methods and demonstrated codes are given too.

Written on December 5, 2014