@Override Tutorial

The @Override is an annotation, an annotation does not change the way your program works, but rather it flags the compiler to be on the lookout for a special condition. When you override a method in a subclass it is a good idea to include the @Override annotation on the line before the method signature. The @Override annotation flags the compiler that the following method is overriding a method in a superclass. If that method does not exist in the superclass, the compiler will generate an error. Discovering an error when overriding a method saves a ton of time, especially if the overloaded method has a small typo in the name. An even better reason for including the @Override is flag someone else who is looking at your code that the method is in fact a overridden method. Without the annotation, the only way to know would be to peck and hunt through the food chain of superclasses. I personally absolutely love it when I see the @Override in Java code. It tells me right off the bat that the programmer who wrote the class had the foresight and took the time to be thorough.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md AtOverride
C:\Java>cd AtOverride
C:\Java\AtOverride>Notepad AtOverride.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class AtOverride {
    public static void main(String args[]) {
        new Child().displayMessage();
        new Parent().displayMessage();
        new GrandParent().displayMessage();
    }
}
class GrandParent {
    void displayMessage() {
        System.out.println("Invoking the method from the GRANDPARENT class.");
    }
}
class Parent extends GrandParent {
    @Override
    void displayMessage() {
        System.out.println("Invoking the method from the PARENT class.");
    }
}
class Child extends Parent {
    @Override
    void displayMessage() {
        System.out.println("Invoking the method from the CHILD class.");
    }
}


Now switch back to the command prompt (CMD) and type in javac AtOverride.java and press Enter.
Now type in java AtOverride and press Enter.


C:\Java\AtOverride>javac AtOverride.java
C:\Java\AtOverride>java AtOverride
Invoking the method from the CHILD class.
Invoking the method from the PARENT class.
Invoking the method from the GRANDPARENT class.


Final thoughts

I did not include the optional @Override in some of my previous tutorials because I try to leave as many optional features out of my tutorials until a time when I can explain the proper implementation. Writing the optional @Override annotation only takes five seconds, but it saves a hundred times that in future headaches. It is a good habit to make.


Tutorials