JVM - subclass method execution order and using @override

This is a newbie question. I read that JVM execution begins by looking for a method name from a junior class in the hierarchy, and if this method is not available in this class, it goes to the parent class, looking for the method.

If so, then why do we need to use "@override" to add custom logic to the inherited class?

The following example illustrates my question.

class superclassA { method() { } } class subclassB extends superclassA { @Override //While executing if JVM starts looking for the method name from the lowest hierarchy //then why do we have to use "override" as the methodname will be matched from the lowest level itself? method() { --custom subclass specific code... } } 
+4
source share
3 answers

If so, then why do we need to use "@override" to add custom logic to the inherited class?

We do not do this. The @Override annotation has no technical meaning - it exists to document the fact that this method overrides one in the superclass, which has some advantages:

  • If you look at the code, it tells you that there is a superclass method that may be important for understanding what this method does
  • You will get a compiler error if the signature of the superclass method changes so that the subclass method does not actually cancel it.
  • You may receive a compiler warning if you override the method without using annotation if you do this unintentionally.
+5
source

@Override simply helps the Java compiler detect errors in the source code; compilers generate an error if the method annotated with @Override does not actually cancel it.

It is not necessary to comment on a method that overrides supertype methods with @Override.

+2
source

You do not need @Override . But this is a useful annotation that makes the compiler check if you are really overriding the method you are talking about. When you @Override method that does not actually override the method, the compiler will inform you of this inconsistency. In addition, this makes the code more understandable: since all methods in Java are implicitly virtual, and a method in a derived class with the same signature as the method is not final in the super class, implicitly overrides it 1 adding @Override makes the code more understandable for people.

1 : To be clear, you cannot have a method in a derived class with the same signature as the final method in the superclass.

+1
source

Source: https://habr.com/ru/post/1493671/


All Articles