What is the reasoning behind not allowing supertypes on Java method overrides?

前端 未结 7 1514
悲哀的现实
悲哀的现实 2021-01-31 10:23

The following code is considered invalid by the compiler:

class Foo {
    void foo(String foo) { ... }
}

class Bar extends Foo {
    @Override
    void foo(Obje         


        
相关标签:
7条回答
  • 2021-01-31 11:23

    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:

    • You want the method in the subclass to override the method in the superclass, or
    • You want the method in the subclass to overload the method in the superclass.

    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.

    0 讨论(0)
提交回复
热议问题