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

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

    If you can override with superclasses, why not with subclasses as well?

    Consider the following:

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

    Now you have succesfully overriden an method whose original parameter was a String to accept a Number. Inadvisable to say the least...

    Instead, the intended results may be replicated by using overloading and the following, more explicit, code:

    class Foo {
        void foo(String foo) { ... }
    }
    
    class Bar extends Foo {
        @Override
        private void foo(String foo) { ... }
        void foo(Object foo) { ... }
    }
    class Another extends Bar {
        @Override
        private void foo(Object foo) { ... }
        void foo(Number foo) { ... }
    }
    

提交回复
热议问题