Annotations like @Override
don't really change the code if I remember correctly, they just provide information to the compiler for error catching.
If a child method is intended to override a parent method, you should ALWAYS use @Override
so the compiler can raise an error if it doesn't actually override anything (e.g. due to spelling error). Below, the two classes A
and B
have the same behaviour - in that they override the method hello()
in the parent class Base
. However, notice the intentional spelling mistake in A
where we typed hwllo()
. The code will not raise any error and the output will appear correct! But if we make the same mistake for class B
then an error will be raised.
class Base {
public void hello() {
System.out.println("Base hello()");
}
}
class A extends Base {
public void hwllo() {
System.out.println("A hello()");
}
}
class B extends Base {
@Override public void hello() {
System.out.println("B hello()");
}
}
class Main {
public static void main(String[] args) {
Base parent = new Base();
A childA = new A();
B childB = new B();
parent.hello();
childA.hwllo();
childB.hello();
}
}
You can find more annotations here https://www.geeksforgeeks.org/annotations-in-java/, some like @Deprecated
tells the user that they shouldn't use a particular method (perhaps due to vulnerability or bad coding practice), but it doesn't change the behaviour of the code at all.