Search code examples
javaannotationsoverriding

How to Add Annotations to Parent Method in Java Without Overriding It?


In Java, how can I add an annotation to a parent method without changing the body of the method. For example:

public class ParentClass {
  public void someMethod() {
    System.out.println("Hello world");
  }
}

public class ChildClass extends ParentClass {
  // Add the @Deprecated annotation to someMethod, without changing its body
}

I need the method to remain the same, but the only difference is now it has an annotation. How would I do this?

I have tried not including a body to the method, ie:

public class ChildClass extends ParentClass {
  @Override
  @Deprecated
  public void someMethod();
}

This doesn't work. I have also tried not using the @Override annotation, but it seems to expect that the method will have a body. Is there a way to just add the annotation without changing its actual value?


Solution

  • If I understood correctly, you can do it like that:

    public class ChildClass extends ParentClass {
        @Override
        @Deprecated
        public void someMethod() {
            super.someMethod();
        }
    }
    

    However, here only calling someMethod on an object declared as ChildClass would be considered as call of a deprecated method. Calling someMethod on an object declared as ParentClass (even if it's actually an ChildClass object) wouldn't be seen as a deprecated method call.