Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JVM - Order of execution of sub class methods and the use of @override [duplicate]

Tags:

java

oop

This is a newbie question. I read that JVM's execution starts from searching for the methodname from lowest class in the hierarchy and if the method is not available in that class it traverses to the parent class looking for the method.

If this is the case then why do we need to use "@override" for adding custom logic to the inherited class ?

The below 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...
} 

}
like image 310
UnderDog Avatar asked Feb 16 '23 18:02

UnderDog


1 Answers

If this is the case then why do we need to use "@override" for adding custom logic to the inherited class?

We don't. 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 there is an superclass method that might be important to understand what this method does
  • You will get a compiler error if the superclass method's signature changes in a way that the subclass method does in fact not override it anymore.
  • You can get a compiler warning if you override a method without using the annotation, in case you do it inadvertantly.
like image 153
Michael Borgwardt Avatar answered Feb 27 '23 09:02

Michael Borgwardt