Home > Blockchain >  Using @Override annotation when child class method signature is changed
Using @Override annotation when child class method signature is changed

Time:06-05

So, I am trying to better understand how Java override works.

I have created this basic code:

     public class A { 
    
       public void foo(String s) {
           System.out.println("inside A");
            }
      }
      public class B extends A{ 
    
       public void foo(String s, String g) {
           super.foo(s);
           System.out.println("inside B");
            }
      }

This code compiles fine, and though the signature is different on the child method (2 arguments instead of one), the usage super does not cause any errors. That, in my eyes means that the compiler understands this as overriding a method.

Yet when I add the @Override annotation on the foo method in class B, then I get a compile error saying:

java: method does not override or implement a method from a supertype

as if my override attempt is no longer correct.

So I am a bit confused as to why this is happening, and what changes when I add the annotation.

CodePudding user response:

"the compiler understands this as overriding a method" - Incorrect, it is NOT an overriding method if the signature is different. The use of super here is redundant, it would work just fine without super.

  • Related