Java - what is "#Override" used for? [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What's “#Override” there for in java?
I've never put "#Override" before a method until now. I see some code examples with it, but I don't understand its utility. I'd love some explanation.
Many thanks,
JDelage

Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.
http://download.oracle.com/javase/6/docs/api/java/lang/Override.html
The case I like to explain its use is when overriding equals.
This will error because equals expects an Object parameter:
public class Foo{
#Override
public boolean equals(Foo f){
return true;
}
}

First, you can't annotate a class with #Override. This annotation indicates that a method declaration is intended to override a method declaration in a superclass.
You don't have to annotate overriding methods but if you use this annotation and your annotated method does not override a superclass method, then the compiler will generate an error message.

The best example - overriding equals().
If you write a class like this:
public class Foo
{
public String bar;
public boolean equals(Foo other)
{
return this.bar.equals(other.bar);
}
}
then you've overloaded the equals method, rather than overriding Object.equals as was intended.
If you annotate the equals method with #Override, the compiler will give you an error stating (correctly) that you haven't overridden a superclass method.
In Java 6, you can use this for implementing interface methods too - this is handy when you're only adding a method to your class to satisfy some interface, and hence the compiler can check that it's required and alert you to the interface changing.
As with all annotations it's effectively a programmatic comment, but having the compiler check that your assumptions are (still) correct is very handy in these cases.

It's there to express that you expect the method to be overriding a superclass method. It does come in handy when you make a mistake spelling the method name or give it the wrong parameters so that it does not override what you thought it was overriding.

It's a conventional comment. Some compilers make sure that the function followed by #Override is actually an override... just a failsafe

Related

Why in both the code snippets '#Override' annotation work properly?

Although the class B implements the interface A, it does not provide the implementation of the method show(). Again, D extends C but in class D the implementation of displayNothing() is the same as the implementation of displayNothing() method in its superclass C.
But in both the cases #Override annotation work properly, why?
//code snippet 1
interface A
{
void show();
}
abstract class B implements A
{
#Override
abstract public void show();
}
//code snippet 2
class C
{
void displayNothing()
{
}
}
class D extends C
{
#Override
void displayNothing()
{
}
}
#Override is only bothered with whether your function name along with the data type is just the same as the method in your super class (with no Alphabetical error). In your case it is the same.Try changing void as int in your class D. It shows a compilation error. As for your abstract class method, it needn't define anything coz the name says it all, it is abstract.
The purpose of the #Override annotation is to prevent bugs. It's presence informs the compiler that there must be a inherited method with that same exact signature that this class is overriding. It does matter if there is an implementation of a method or not.
It is perfectly legal to not include an #Override annotation. The potential problem you might encounter, though, is if you accidentally had a typo or inadvertently changed the method signature, you would be overloading the method, not overriding it. The compiler would not be able to catch this bug. The program might crash or it might even run, but run incorrectly.
Because this might be a difficult bug to spot, especially with methods containing several parameters, the #Override annotation was created. The #Override annotation informs the compiler that this method is an override, not an overload and if the compiler fails to find a method to override, return a compilation error.
All these methods would compile and could be run but none would override the displayNothing() method.
void displayNothng();
void displaynothing();
void displayNothing(String value);
The #Override annotation "works properly" in both presented cases, because java reuses this annotation for interfaces and classes, even if you feel that the first and the second snippet of code do something different it's just not as important to introduce separated keywords/annotations to differentiate between overriding from an interface and from a class. Even an abstract class doesn't change things here.
The #Override indicates that a given method has a compatible representation in the super class/interface, it's used to ensure we don't have any syntax issue in the definition.
B is abstract. Abstract classes don’t need to provide implementations. If an abstract class doesn’t implement a required method it doesn’t matter. If a class isn’t abstract, then implementations of all abstract methods need to be there.
D provides an override of the displayNothing method in C. The compiler doesn’t check whether the overridden version is the same as the overriding version, and it doesn't care if the overriding implementation is empty. All the Override annotation does is confirm that there is a method with the same signature above the annotated one in the class hierarchy.
The purpose of the annotation is to confirm that you’re actually overriding an existing method and haven’t introduced a bug by misspelling the method name or otherwise not matching the signature of the method you mean to override. See the Java Language Specification, 9.6.4.4, where it says:
Programmers occasionally overload a method declaration when they mean to override it, leading to subtle problems. The annotation type Override supports early detection of such problems.
The classic example concerns the equals method. Programmers write the following in class Foo:
public boolean equals(Foo that) { ... }
when they mean to write:
public boolean equals(Object that) { ... }
This is perfectly legal, but class Foo inherits the equals implementation from Object, which can cause some very subtle bugs.
(Be aware when I describe what #Override does I'm skipping over override-equivalence because you didn't ask about it and there are already perfectly good answers that cover that.

How #override works in java

I see that the #override annotation is marker annotation. How does the compiler knows what to do with this annotation? Where is the logic to check if a method really overrides the super class method?
I guess it regards all annotaions since there a logic free
The standard documentation answers this nicely.
#Override #Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance.
// mark method as a superclass method
// that has been overridden
#Override
int overriddenMethod() { }
While it is 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.
You can create your own annotations and then use the api java reflection to process this annotations.
this link may help as a start

JVM - Order of execution of sub class methods and the use of #override [duplicate]

This question already has answers here:
When do you use Java's #Override annotation and why?
(27 answers)
Closed 9 years ago.
This is a newbie question.
I read that JVM's execution starts from searching for the methodname from lowest class in the hierarchy and if the method is not available in that class it traverses to the parent class looking for the method.
If this is the case then why do we need to use "#override" for adding custom logic to the inherited class ?
The below example illustrates my question
class superclassA
{
method()
{
}
}
class subclassB extends superclassA
{
#Override
//While executing if JVM starts looking for the method name from the lowest hierarchy
//then why do we have to use "override" as the methodname will be matched from the lowest level itself?
method()
{
--custom subclass specific code...
}
}
If this is the case then why do we need to use "#override" for adding custom logic to the inherited class?
We don't. The #Override annotation has no technical meaning - it exists to document the fact that this method overrides one in the superclass, which has some advantages:
If you look at the code, it tells you there is an superclass method that might be important to understand what this method does
You will get a compiler error if the superclass method's signature changes in a way that the subclass method does in fact not override it anymore.
You can get a compiler warning if you override a method without using the annotation, in case you do it inadvertantly.
#Override simply helps Java compiler detect errors in source code, compilers are generate an error if a method annotated with #Override does not override it in fact.
It is not mandatory to annotate a method that overrides a supertype methods with #Override.
You don't need #Override. But it's a useful annotation that causes the compiler to check whether or not you are really overriding the method that you say you are. When you #Override a method that is not actually overriding a method, the compiler will inform you of this discrepancy. Additionally, it just makes your code more clear: since all methods in Java are implicitly virtual, and a method in a derived class with the same signature as that of a non-final method in a super class implicitly overrides it1, adding #Override makes the code easier for humans to understand.
1: To be clear, you can not have a method in a derived class with the same signature as a final method in a super class.

any annotation equivalent to #Override for overriding (hiding) static methods?

as it is explained here, in java static methods are not overridden but hidden by child implementations
that means that you can't use #Override annotations with them
the following code
#Override
public static void test(String value1, String value2) {
gives this compiler error.
The method test(String, String) of type Child must override or implement a supertype method Child.java
is there some equivalent annotation that I could use to make sure my class is "hiding" an existing static method from parent class?
This is an easy one: No.
Check out the list of standard compiler annotations
I am not aware of any annotations that you can add. But simply creating the method with the exact same name and inputs (the same method signature) should hide it. The only way to know for sure is to know the details of the superclass method for sure, and then perhaps test your method... Thats all I can think of. The only other annotations I can think of would be to suppress warnings which would be the opposite of what you want I imagine. Whenever I hide a method like this I generally get a warning from my IDE telling me that I am hiding another method.

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

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?
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.
Override annotation is a compile time annotation which makes java compiler throw an error if the method having this annotation is actually not overriding a parent class method.
You can try to change the Wolf class to not extend the Animal class and if Override annotation is present it will show you a compile time error
something like it alerts at compile time by throwing compilation error if you are not really overriding the method.
similar Q here-When do you use Java's #Override annotation and why?
It works as a comment, but also as an assertion that you actually ARE overriding something. If you use #Override, but it does not actually override anything, the compiler will generate an error. See the documentation page for more details.
If you remove the "eat" method from the parent class or misspell it as "eats" in the subclass, your code will now fail to compile. Without the "#Override" annotation, you can do either and your code will still compile, it just won't do what you want (namely, override a method).
It does not do anything at run-time, but it helps you to catch errors:
If you thought you would override a method, but do not (because of a speling problem or parameter types), without the annotation, the code would compile to something useless (as in: your method would not be called, but the superclass method that you accidentally did not override gets called).

Categories

Resources