Monday 30 May 2016

Which constructor is called and why?


public class TestConstruct {

     public TestConstruct(Integer a) {
           System.out.println("It is an Integer");
     }

     public TestConstruct(long b) {
           System.out.println("It is a long");
     }

     public TestConstruct(int...x) {
           System.out.println("It is a int...");
     }

     public static void main(String[] args) {
           new TestConstruct(8);

     }
}

Output:
It is a long

Reason:
The general thumb rule is Widening (smaller primitive data type)> Autoboxing (wrapper) > Varargs.

public class TestConstruct {

            public TestConstruct(Integer a) {
                        System.out.println("It is an Integer");
            }

            public TestConstruct(long b) {
                        System.out.println("It is a long");
            }

            public TestConstruct(int... x) {
                        System.out.println("It is an int...");
            }

            public TestConstruct(int b) {
                        System.out.println("It is an int");
            }
           
            public static void main(String[] args) {
                        new TestConstruct(8);

            }
}
Output:
It is an int


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...