The JVM doesn't care about the @Override
annotation. As you can see, its retention policy is SOURCE
. The annotation exists only in the source code, not at runtime, and not in the compiled class files either. The JVM cannot check for it.
How @Override
works is specified in the Java Language Specification, specifically, here. Here are some relevant quotes:
Programmers occasionally overload a method declaration when they mean to override it, leading to subtle problems. The annotation interface Override supports early detection of such problems.
If a method declaration in class or interface Q
is annotated with
@Override
, then one of the following three conditions must be true,
or a compile-time error occurs:
- the method overrides from
Q
a method declared in a supertype of Q
- the method is override-equivalent to a public method of
Object
Q
is a record class, and the method is an accessor method for a record component of Q
It is up to whoever is writing the compiler for Java, to implement these rules. The body of the declaration for @Override
is empty, because it doesn't need anything in there. It is the compiler that does the hard work to follow the above rules. The compiler finds where you have used @Override
, and does a bunch of checks.
The declaration itself still needs to be there, because the language specifications mandates it.
Also, note that whether a method overrides another is not determined by the existence of @Override
. The conditions for overriding is specified in another section of the language specification. Notably, the list of conditions does not include anything about the @Override
annotation.
As said in the quote above, @Override
is just a way to ensure you don't write something that you thought overrides another method, but in fact doesn't.
At runtime, the JVM finds the correct method to call using its own rules of overriding that just so happens to closely match the rules of the Java language. Whoever is writing an implementation for the JVM has to follow those rules. This process is called "Method Selection", and does not involve @Override
at all.