What is the purpose of @Override?

Asked

Viewed 58,057 times

50

I’m having some doubts about @override, read somewhere and remember vaguely on the question of rewriting, but what is it? And what is it for? How does it apply in a code JAVA. Exists in some other language?

  • http://www.k19.com.br/artigos/para-que-serve-a-anotacao-override-da-linguagem-java/

4 answers

67


It is a way to ensure that you are overwriting a method and not creating a new one.

Let’s assume you created a class with a print method:

public class SuperClasse {
    public void imprime() {
        System.out.println("imprime");
    }
}

So you’ve 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 overwritten the method imprime() and the above code will work without major problems.

However one fine day you decided to change the name of the method in the Superclass of imprime() for 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 method imprime() in which is not overwriting the method in the Superclass. You’re actually calling a new method, which is called imprime().

What would happen if you had used the Annotation @Override ?

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 of imprime() for imprimir() you will no longer be able to compile your code because @Override will notice that you are not overwriting anything, as there is no other method imprime() in the Superclass.

You will receive the following error:

Mydomain must override or implement a supertype method

In free translation (good):

Minhaclasse must override or implement a method of its super class

All object-oriented language allows superscription of super-class methods by the daughter class. However, each programming language uses its own means to deal with this superscript. Java has chosen to use Annotation @Override for developers who want the security cited in the course of the response, however, nothing requires the use of this Annotation.

C# also has such functionality, however it does not use Annotation, it incorporates the reserved word override in the method declaration:

public override int Area()
{
    return side * side;
}

It is impossible to list all the programming languages that make use of override Believe it or not, there are thousands (literally!) of languages out there. If you want a more complete list see: Wikipedia - Method Overriding

  • 3

    What an incredible response, congratulations on the great shared knowledge!

18

What is Override in Object Oriented Programming?

Rewriting a method that has been inherited, where his behavior in the Father class differs from his behavior in the daughter class. That is, they have the same name, but different functionalities or actions. Obs: If you do not rewrite the method it will have the behavior of the Parent class, which by logic there is only one implementation.

Exists in other languages?

In Object-Oriented languages, this is a trivial factor, there are in them perhaps what changes is their form of implementation.

Example:

public class Pai {    
    public int Soma(int value){
        return value + 100;
    }
}

public class Filho extends Pai {
    @Override
    public int Soma(int value){
        return value + 200;
    }
}

Coding

public static void main(String[] args) 
{
    Pai pai = new Pai();
    System.out.println(pai.Soma(1));

    Filho filho = new Filho();        
    System.out.println(filho.Soma(1));
}

Upshot

inserir a descrição da imagem aqui

Note that in the Parent class the value is one and in the Daughter class is another, that is, as it was rewritten, you can have different behaviors in the classes

14

Superscript or Override

The superscript of a method occurs when a daughter class implements a method that already exists in a mother class, changing (overwriting) existing behavior.

Example:

public class Gato {
    public void falar() {
        System.out.println("Miau");
    }
}

public class Gatinho extends Gato {
    public void falar() {
        System.out.println("Mew");
    }
}

In the example above, the class Gatinho inherits the class Gato, but changes the behavior of the method falar().

If we call the methods polymorphically, the result is different. Example:

Gato gato = new Gato();
gato.falar();
Gatinho gatinho = new Gatinho();
gatinho.falar();
Gato gatoPolimorfico = new Gatinho();
gatoPolimorfico.falar();

The result will be:

Meow

Mew

Mew

Class java.lang.Object

Specifically in the Java language, there is the class Object who is the mother of all other classes. This means that even though we do not have a extends in the declaration, every class has an implicit inheritance.

The class Object has some special methods. One of them is the toString(), used to "represent" an object in the form of String. In that case, we could overwrite the same method without having an explicit inheritance.

Example:

public class Gato {
    public String toString() {
        return "Sou um Gato";
    }
}

Signatures of the superscripted methods

There is a detail of the superscript of methods that has not been mentioned and often causes problems: to overwrite a method, you must keep exactly the same signature.

What is a signature in the Java language? It is the composition of the elements that declare the method.

Consider the following signature:

public String setNome(String nome) throws IllegalArgumentException

Now consider the elements that are part of a method declaration:

  • Access modifiers: public, private, protected
  • Other modifiers: static, native, synchronized
  • Type of Return: String, int
  • Method name: setNome
  • Types and Names of Parameters: String nome
  • Exceptions declared: IllegalArgumentException

Specifically in Java, method superscript occurs if at least the name and type of the parameters are equal.

The following example describes a overload (Overload) method and not a superscript:

public class OutroGatinho extends Gato {
    public void falar(String frase) {
        System.out.println(frase);
    }
}

In the class above, consider the first example, the method falar(String) nay is overwriting the method falar() class Gato, because the signature is different.

Another feature of the Java language is that it differentiates between upper and lower case (case sensitive). This can lead to misunderstandings, such as the following example:

public class Gato {
    public String tostring() {
        return "Sou um Gato";
    }
}

Note that the s is tiny in tostring. This causes the above method not to be called as expected!

Annotation @Override to the rescue!

Then came the note @Override. It simply informs the compiler that the intent would overwrite.

In this way, the compiler can evaluate whether the signature is consistent with some superclass method and issue a warning if the method is not actually overwriting something!

So, in the example of tostring tiny, it would be evident to the developer that there has been some misconception.

In addition, it is common when a system’s code is modified or libraries are updated, for methods that the developer has overwritten simply stop being called without warning. This is because a method of a superscript class has been changed or removed. With the annotation @Override, you become more "safe" to make this kind of change and be able to track the points of code that need attention.

1

Overwriting ( overload ) methods is part of the object orientation that I will not go into detail, since the question is directed to annotation.

The annotation basically serves to "warn" the compiler that that method is overwriting ( Overriding ) a superclass method from which he extends.

  • 3

    Overwriting and overwriting are separate things, no!?

  • That answer is a little confusing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.