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

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

    The answer is plain simple, in Java, for method overriding, you must have the exact signature of the super type. However, if you remove the @Override annotation, your method would be overloaded and your code won't break. This is a Java implementation that ensures that you mean the method implementation should override the implementation of the super type.

    Method overriding works in the following way.

    class Foo{ //Super Class
    
      void foo(String string){
    
        // Your implementation here
      }
    }
    
    class Bar extends Foo{
    
      @Override
      void foo(String string){
        super(); //This method is implied when not explicitly stated in the method but the @Override annotation is present.
        // Your implementation here
      }
    
      // An overloaded method
      void foo(Object object){
        // Your implementation here
      }
    }
    

    The methods shown above are both correct and their implementation can vary.

    I hope this helps you.

提交回复
热议问题