0

I have two sample program to understand parameter casting in Java.

Program 1:

public class TestRunner {

    public static void main(String[] args) {

        TestRunner r = new TestRunner();
        r.call(null);
     }

    void call(Object obj){
        System.out.println("I am from object");
    }
    void call(String obj){
        System.out.println("I am from string");
    }

 }

Program 2:

public class TestRunner {

    public static void main(String[] args) {

        TestRunner r = new TestRunner();
        r.call(null);
     }

    void call(Object obj){
        System.out.println("I am from object");
    }
    void call(String obj){
        System.out.println("I am from string");
    }

    void call(Integer obj){
        System.out.println("I am from Integer");
    }
 }   

Program 1 prints "I am from string" Program 2 giving compilation error.

Please Explain me how its work.

Gan
  • 624
  • 1
  • 10
  • 31
  • Duplicate! Duplicate! Just let me find it.... – dryairship Jun 06 '16 at 12:15
  • 2
    The most specific method gets called. In the first case `String` is more specific than `Object`, hence the `call(String)` gets called. In the second example `String` and `Integer` are equally specific, hence the compiler doesn´t know which method to call -> compiler error. – SomeJavaGuy Jun 06 '16 at 12:15
  • Oh! @Pshemo already did. – dryairship Jun 06 '16 at 12:16
  • 2
    Try googling your problem using for instance query `java method ambiguous null site:stackoverflow.com`. You should find many answers on this subject. – Pshemo Jun 06 '16 at 12:17

0 Answers0