Monday, 30 May 2016

Which constructor is called and why?


public classTestConstruct {

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

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

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

     public static voidmain(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(longb) {
                        System.out.println("It is a long");
            }

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

            public TestConstruct(intb) {
                        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...