The following code is considered invalid by the compiler:
class Foo {
void foo(String foo) { ... }
}
class Bar extends Foo {
@Override
void foo(Obje
Java annotations cannot change the way the compiler generates byte code from your classes. You use annotations to tell the compiler how you think your program should be interpreted, and report errors when compiler's interpretation does not match your intentions. However, you cannot use annotations to force the compiler to produce code with different semantics.
When your subclass declare a method with the same name and parameter count as in its superclass, Java must decide between two possibilities:
If Java allowed foo(Object)
to override foo(String)
the language would have to introduce an alternative syntax for indicating an intent to overload a method. For example, they could have done it in a way similar to C#'s new
and override
in method declarations. For whatever reason, however, the designers decided against this new syntax, leaving the language with the rules specified in JLS 8.4.8.1.
Note that the current design lets you implement the functionality of an override by forwarding the call from the overloaded function. In your case, that would mean calling Bar.foo(Object)
from Foo.foo(String)
like this:
class Foo {
public void foo(String foo) { ... }
}
class Bar extends Foo {
@Override
public void foo(String foo) { this.foo((Object)foo); }
public void foo(Object foo) { ... }
}
Here is a demo on ideone.