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

前端 未结 7 1518
悲哀的现实
悲哀的现实 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

    Suppose you could do that. Now your superclass looks like this:

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

    and your subclass now:

    class Bar extends Foo {
        @Override
        void foo(Object foo) { ... }
    }
    

    The language probably could allow such a thing (and just dispatch both Foo.foo(String) and Foo.foo(Number) to Bar.foo(Object)), but apparently the design decision for Java here is that one method only can override exactly one other method.

    [Edit]

    As dasblinkenlight said in his answer, one can have a foo(Object) without the @Override, but this just overloads the foo functions, and does not override them. When calling, java chooses the most specific method, so foo("Hello World") would always get dispatched to the foo(String) method.

提交回复
热议问题