java - method signature in inheritance -
in code below
class { public void v(int... vals) { system.out.println("super"); } } class b extends { @override public void v(int[] vals) { system.out.println("sub"); } }
then can call new b().v(1, 2, 3);//print sub rather super
ridiculous does work well. if change b
class b { public void v(int[] vals) { system.out.println("not extending a"); } }
the call new b().v(1, 2, 3);
invalid. have call new b().v(new int[]{1, 2, 3});
, why?
under jdk 1.7, neither of examples compiles, , don't believe should.
it's easy see why second version doesn't - when b
doesn't extend a
, there's no indication of varargs @ all, there's no reason why compiler should possibly convert argument list of 3 int
arguments single int[]
. more interesting situation b
does extend a
.
the compiler finds signature of v(int[] vals)
doesn't use varargs. there's nothing in spec should inheritance chain find whether 1 of other declarations (there multiple ones) uses varargs. fact appears in version of jdk 1.6 suggests compiler bug has since been fixed. (i've reproduced bug in jdk 1.6.0_39 well.)
basically, if want able invoke b.v()
in varargs-style syntax, b.v()
should declared using varargs. of course, if change compile-time type a
, work:
a = new b(); a.v(1, 2, 3);
or (ick):
((a) new b()).v(1, 2, 3);
note if compile -xlint
warning b
anyway:
test.java:14: warning: v(int[]) in b overrides v(int...) in a; overriding method missing '...' public void v(int[] vals) { ^
Comments
Post a Comment