Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's "@Override" there for in java?

Tags:

java

syntax

public class Animal {
   public void eat() { System.out.println("I eat like a generic Animal."); }

}

public class Wolf extends Animal {
   @Override
   public void eat() { System.out.println("I eat like a wolf!"); }
}

Does @Override actually have some functionality or it's just kinda comment?

like image 728
symfony Avatar asked Mar 22 '10 04:03

symfony


1 Answers

From the Java Tutorials on annotations:

@Override — the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass (overriding methods will be discussed in the the lesson titled "Interfaces and Inheritance").

   // mark method as a superclass method
   // that has been overridden
   @Override 
   int overriddenMethod() { }

While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

Let's take a look at the example given in the Java Language specifications, 9.6.1.4 Override. Let's say you want to override a method, equals in that case, but you wrote:

    public boolean equals(Foo that) { ... }

instead of:

    public boolean equals(Object that) { ... }

While this code is legal, annotating the equals method declaration with @Override would trigger a compile time error because you're in fact not overriding it, you're overloading it. This can cause nasty bugs and the Override annotation type helps at detecting them early.

like image 75
Pascal Thivent Avatar answered Sep 21 '22 22:09

Pascal Thivent