Home > Mobile >  foo(int, int) is picked over foo(int...)
foo(int, int) is picked over foo(int...)

Time:06-28

In this piece of code, why the compiler is not able to reference the method that has varargs argument from static context.

 private static void doSomething(int... nums) {
    System.out.println("1");
}
private void doSomething(int num1, int num2) {
    System.out.println("2");
} 

public static void main(String[] args) {
    doSomething(1,2);
}

JDK 17 is complaining Cannot make a static reference to the non-static method doSomething(int, int) . Is this a bug or another feature I am not aware of.

JDK 8 and JDK 11 dont complain about it!

CodePudding user response:

The doSomething method which takes two ints is an instance method and you are trying to call it without creating an instance of the object first.

Why should the compiler accept that? I highly doubt, that in any prior JDK it behaved differently.

CodePudding user response:

A static method can call only other static methods; it cannot call a non-static method. So that's why the non-static doSomething function is always called.

In order to call the doSomething(int, int) you have to make it static or create an object of the class containing the method and then call the method using the object.

YourClass obj = new YourClass();
obj.doSomething(1, 2);

CodePudding user response:

varargs are replacement for arrays. Compiler is giving you error because you are calling doSomething in a manner which is not acceptable for varargs:

To call your varargs method you should call something like:

doSomething(new int [] {1,2});

By this way, you will be correctly calling private static void doSomething(int... nums)

  • Related