Java @override Annotations - What does it mean ?

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. This is extremely useful to quickly identify typos or API changes. Let's look at an example.

The first class is Animal that has one class method. Its will be used as the superclass.

package com.as400samplecode;

public class Animal {
    public void myMethod() {
        System.out.println("The instance method in Animal.");
    }
}

A subclass of Animal, is called Cat. This overrides the method myMethod()

package com.as400samplecode;

public class Cat extends Animal {

    @Override
    public void myMethod() {
        System.out.println("The instance method in Cat.");
    }

}

Now if I make a mistake in typing the correct method name then the compiler will give me an error only when i use the @Override annotation - The method myMethod() of type Cat must override a superclass method

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.