Two constructors having same no. of parameters but different data types

660 Views Asked by At

Here when I run this below code I get called as the output and I was wondering why not called new. Since 1 comes under both short and int range.

public class MyClass {

        private int x;

        public MyClass(){
            this(1);
        }

        public MyClass(int x){
            System.out.println("called");
            this.x = x;
        }

       public MyClass(short y){
            System.out.println("called new");
            this.x = y;
        }

        public static void main(String args[]) {
        MyClass m = new MyClass();
            System.out.println("hello");
        }
    }
2

There are 2 best solutions below

2
On

1 is an int literal, so MyClass(int x) is chosen.

Even if you remove the MyClass(int x) constructor, MyClass(short y) won't be chosen. You'll get a compilation error instead, since 1 is not short.

You'll have to cast 1 to short - this((short)1); - in order for the MyClass(short y) to be chosen.

0
On

As an addition to others answer I can suggest you to check which constructors are being called when you initialize variables of other types using the same literal:

short s = 1;
int i = 1;

And then check which constructor of MyClass is being called as you call them with above arguments.