@Override
sentence uses comment syntax. This sentence lets to the Java compiler know that you want to override an existing method of a parent class (overwrite how a function works in this class while it exists in the parent class).
For example, the following class
public class Base {
public void saySomething() {
System.out.println("Hi, I'm a base class");
}
}
public class Child extends Base {
@Override
public void saySomething() {
System.out.println("Hi, I'm a child class");
}
}
In this case we are overriding what saySomething
method does in the Child class, therefore if you use it somewhere, for example:
public static void main(String [] args) {
Base obj = new Child();
obj.saySomething();
}
The expected output will be : "Hi, I'm a child class". Is important to know that @Override
only works for public and protected functions.
In Java 6, it also mean you are implementing a method from an interface.
However that's not the only function of @Override, it will be a potential help to quickly identify typos or API changes in the methods. Analize the following example:
public int multiplyinteger()
public int multiplyInteger()
Do you find something weird ? Nope ? (Look for uppercases in some of the methods). That's right, if the method is named multiplyinteger but you call it multiplyInteger, you'll never know what's going on because indeed, nothing will happen.
This function will be not executed because it simply doesn't exists, however if you use @Override
you'll get a clear warning or error when trying to compile. Adding @Override
to a method makes it clear that you are overriding the method and make sure that you really are overriding a method that exists.