gstackoverflow
gstackoverflow

Reputation: 37038

method rules overloading explanation in java

I try to understand overloading rules which uses java compiler.

it is too hard for me.

public class Main {

    public static void var(Long x) {
        System.out.println("Long");
    }

    public static void var(int... x) {
        System.out.println("int... x");
    }


    public static void main(String... args) {
          var(5);
    }
}

output:

int...

In Internet I found next rules:

  1. Primitive Widening > Boxing > Varargs.
  2. Widening and Boxing (WB) not allowed.
  3. Boxing and Widening (BW) allowed.
  4. While overloading, Widening + vararg and Boxing + vararg can only be used in a mutually exclusive manner i.e. not together.
  5. Widening between wrapper classes not allowed

but I cannot apply this rules to this code behaviour.

Can you help me?

my wrong version:

boxing int -> Integer and widening to Long

Additional question

public class Main {

    public static void var(Object x) {
        System.out.println("Object");
    }

    public static void var(int... x) {
        System.out.println("int... x");
    }


    public static void main(String... args) {
          var(5);
    }
}

output:

object

Upvotes: 2

Views: 159

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213311

boxing int to Integer and widening to Long

Although int to Integer boxing is fine, but Integer to Long is not a valid widening. Long is not supertype of Integer. So that's not valid. One option is widening followed by boxing. But such conversion is not allowed in Java. So the only option that is left is using varargs.

Upvotes: 2

Related Questions