Question:
I have some doubts about @override
, read it somewhere and vaguely remember the rewrite issue, but what is it? And what is it for? How to apply in a JAVA code. Does it exist in any other language?
Answer:
It is a way to ensure that you are overwriting a method and not creating a new one.
Let's say you created a class with a print method:
public class SuperClasse {
public void imprime() {
System.out.println("imprime");
}
}
So you made a class that extends this class, and you want to change what will be printed when the method is called:
public class MinhaClasse extends SuperClasse {
public void imprime() {
System.out.println("imprime diferente");
}
}
You have correctly overridden the imprime()
method and the code above will work without any major problems.
However one fine day you decided to change the name of the method in the SuperClass from imprime()
to imprimir()
:
public class SuperClasse {
public void imprimir() {
System.out.println("imprime");
}
}
If you don't remember the class that extended the SuperClass you will have a imprime()
method on it that is not overriding the method on the SuperClass . You're actually calling a new method, which is called imprime()
.
What would happen if you had used @Override annotation ?
This would be your code in principle for the two classes:
public class SuperClasse {
public void imprime() {
System.out.println("imprime");
}
}
public class MinhaClasse extends SuperClasse {
@Override
public void imprime() {
System.out.println("imprime diferente");
}
}
So far, nothing new. However when you change your method from imprime()
to imprimir()
you will no longer be able to compile your code as @Override will notice that you are not overwriting anything as there is no longer any imprime()
method in the SuperClass.
You will receive the following error:
MyClass must override or implement a supertype method
In free (good) translation:
MyClass must override or implement a method of your super class
Every object-oriented language allows superclass methods to be overridden by the child class. However, each programming language uses its own means to deal with this overwrite. Java has chosen to use the @Override annotation for developers who want the security mentioned throughout the answer, however, there is no obligation to use this annotation.
C# also has such functionality, though it doesn't use annotation, it incorporates the override
keyword in the method declaration:
public override int Area()
{
return side * side;
}
It's impossible to list all the programming languages that use the override
because believe it or not, there are thousands (literally!) of languages out there. If you want a more complete list see: Wikipedia – Method overriding