简体   繁体   中英

Resolve Java method with omitted varargs parameter

I have the following classes definition:

class A {
String foo(Object par) {
     return par.toString();
  }
}
class B extends A {
 static String foo(String par, Object ... pars) {
   return par.toString();
 }
}

If I do a call like B.foo("hello"); , then I get a compilation error

error: non-static method foo(Object) cannot be referenced from a static context

Of course B.foo("hello", (Object[])null); works just right. However if I rename the virtual method foo, to foo1 for example, then the compilation error gets gone. It means that first variant of a static method call is still valid, however a compiler tries first to match virtual signature. Can someone provide a right explanation the behavior from the Java language specification document?

The method resolution algorithm is defined in the JLS #15.2.2 . In substance, methods without varargs have priority over methods that have varargs (emphasis mine):

The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation . If no applicable method is found during this phase then processing continues to the second phase.

As explained in the JLS, it is done that way " to ensure compatibility with versions of the Java programming language prior to Java SE 5.0 ".

A.foo is NOT static while B.foo is.

Calling B.foo("Hello") is an error because inherited A.foo method is NOT static. The calls that you say are working probably shows you a warning?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM