1

I need some help in understanding the concept. Please refer following example and how code shows different outputs?

Scenario-1: If I used public Confusing(Object o){ this method signature then output is object, but if I used public Confusing(StringBuffer sb){ String Buffer output is printing?

public class Confusing {
    public Confusing(Object o){
        System.out.println("Object");
    }
    public Confusing(StringBuffer sb){
        System.out.println("String Buffer");
    }
    public static void main(String[] args) {
        new Confusing(null);
    }
}

Scenario-2: If I used use public Confusing(Object o){ this method signature then output is object, but if I used public Confusing(double[] dArray){ then why output is Double Array?

    public class Confusing {
    public Confusing(Object o){
        System.out.println("Object");
    }
    public Confusing(double[] dArray){
        System.out.println("Double Array");
    }
    public static void main(String[] args) {
        new Confusing(null);
    }
}

Scenario-3 If I used following code then why I'm getting following error? How we can fixed this error?

The constructor Confusing(Object) is ambiguous

public class Confusing {
    public Confusing(Object o){
        System.out.println("Object");
    }
    /*public Confusing(double[] dArray){
        System.out.println("Double Array");
    }*/
    public Confusing(String s){
        System.out.println("String");
    }
    public Confusing(StringBuffer sb){
        System.out.println("String Buffer");
    }
    public static void main(String[] args) {
        new Confusing(null);
    }
}

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The constructor Confusing(Object) is ambiguous

Kindly help me to understand the concept.

  • Your description of scenario 2 doesn't match the code. It would help if in each case you would just show the code you're running, without anything commented out. Also, it's best not to *try* to run code that doesn't compile. Don't wait to get an exception - just make sure the code compiles before you run it! – Jon Skeet Dec 13 '15 at 17:45
  • Simply help to understand the concept for 1st and 2nd scenario, I will update details for 3rd scenario –  Dec 13 '15 at 17:46
  • Even the first scenario is confusing, because you haven't shown the code. – Jon Skeet Dec 13 '15 at 17:49
  • Other possible duplicate is this: [Which overload will get selected for null in Java?](http://stackoverflow.com/q/1545501) – Tom Dec 13 '15 at 17:51
  • 1
    Hi Tom - Great link, you solved all my problems, cheers, Thanks, Kalpita –  Dec 13 '15 at 17:53

0 Answers0