简体   繁体   中英

Using @Override annotation when child class method signature is changed

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.

"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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM