Varargs with inheritance in Java

367 Views Asked by At

Suppose I have a class Foo like so:

public class Foo<T> {
    protected T invoke(Object... args);
}

Now suppose I add this:

public class Bar<T, Arg> extends Foo<T> {
    public T invoke(Arg arg);
}

Does this mean that I cannot create a Bar<T, Object[]> since it would create two invoke() methods with "essentially" the same signature? Or would Bar.invoke() safely hide Foo.invoke() in this case (as Bar.invoke() is, runtime-wise, taking Object rather than the Object[] of Foo.invoke())?

Related to this: is forwarding Bar.invoke() to Foo.invoke() safe and fine?

1

There are 1 best solutions below

0
On BEST ANSWER

Bar.invoke does not override Foo.invoke. If you call just bar.invoke with no arguments you'll get the foo.invoke called.

But you'll get a compile time error (reference to invoke is ambiguous) if you construct a Bar object: Bar<Object, Object[]> bar = new Bar<Object, Object[]>() and then invoke bar.invoke(new Object[]{}) because the 2 invoke methods have the same erasure at runtime.