Java @Override: Usage Guide
In Java, @Override is an annotation used to indicate that a method is overriding a method from a parent class or implementing a method from an interface. It helps developers in checking if a method is correctly overriding a method from a parent class or interface.
The use of the @Override annotation helps remind the compiler to check if the signature of a method (method name, parameter list, and return type) matches that of a method in the superclass or interface. If there is a mismatch, the compiler will throw an error, thereby preventing potential mistakes.
Here is how to use the @Override annotation:
- When a method is marked as @Override, it must exist in the parent class, otherwise it will result in a compilation error.
- The method signature must be identical to the method being overridden, including the method name, parameter list, and return type.
- This can only be used for methods, not for other members such as properties or constructors.
- The @Override annotation is just a marker that can be optionally used, but it is recommended to use it as it can enhance the readability and maintainability of the code.
The example code is as follows:
class SuperClass {
public void printMessage() {
System.out.println("Hello, World!");
}
}
class SubClass extends SuperClass {
@Override
public void printMessage() {
System.out.println("Hello, Java!");
}
}
In the above example, the SubClass class utilizes the @Override annotation to override the printMessage method from the parent class SuperClass. Without using the @Override annotation, the compiler would not detect this error.