When do you use Java's @Override annotation and why?
Asked Answered
E

27

498

What are the best practices for using Java's @Override annotation and why?

It seems like it would be overkill to mark every single overridden method with the @Override annotation. Are there certain programming situations that call for using the @Override and others that should never use the @Override?

Eulogium answered 18/9, 2008 at 16:48 Comment(0)
S
515

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

Sarrusophone answered 18/9, 2008 at 16:53 Comment(10)
Along the same lines as "easier to understand", the IDEs will spot the @Override annotation and visually flag the overriding method in the editor.Filamentary
Some IDEs will flag an overridden method that is missing the @Override annotation as well.Leastwise
The other benefit is that if the parent class changes, the compiler will make sure that the child classes have been updated as well.Damalis
@Jay R.: True. As a matter of fact, e.g. Eclipse can even automatically add the @Override if it is missing.Quechuan
In case anyone else got here because of the apparently undocumented change from 1.5 to 1.6 for @Overrides on methods coming from interfaces, bugs.sun.com/bugdatabase/view_bug.do?bug_id=5008260 seems to be the corresponding bug. (Thanks for pointing it out, Dave L.!)Womenfolk
It seems the same situation as with exceptions throws-keyword. We were provided with so much control that last tendency is to derive from RuntimeException to avoid thinking about exception more than about logic of the applicationFootloose
@hheimbuerger Thanks man, I really wondered if Eclipse was kidding me... then I googled and came right here... again. I already upvoted your comment... doohIncalescent
ay, years old, and just helped me realize that my code is 1.5 and marked an error for override on interface method ;)Allopatric
You can configure Eclipse to automatically insert missing @Override annotations: see Project > Save Actions > Configure.Jeffiejeffrey
Your comment on @Implements was right on with my thoughts. I came here to see if @Override was correct for implementation methods, and from what I gather here it is. Thanks. I agree that @Implements would be better. It would also cause less confusion.Most
S
110

I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:

protected boolean displaySensitiveInformation() {
  return false;
}

You will often see something like the above method that overrides a method in the base class. This is an important implementation detail of this class -- we don't want sensitive information to be displayed.

Suppose this method is changed in the parent class to

protected boolean displaySensitiveInformation(Context context) {
  return true;
}

This change will not cause any compile time errors or warnings - but it completely changes the intended behavior of the subclass.

To answer your question: you should use the @Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.

Sanctum answered 18/9, 2008 at 16:56 Comment(0)
C
46

There are many good answers here, so let me offer another way to look at it...

There is no overkill when you are coding. It doesn't cost you anything to type @override, but the savings can be immense if you misspelled a method name or got the signature slightly wrong.

Think about it this way: In the time you navigated here and typed this post, you pretty much used more time than you will spend typing @override for the rest of your life; but one error it prevents can save you hours.

Java does all it can to make sure you didn't make any mistakes at edit/compile time, this is a virtually free way to solve an entire class of mistakes that aren't preventable in any other way outside of comprehensive testing.

Could you come up with a better mechanism in Java to ensure that when the user intended to override a method, he actually did?

Another neat effect is that if you don't provide the annotation it will warn you at compile time that you accidentally overrode a parent method--something that could be significant if you didn't intend to do it.

Circumspection answered 18/9, 2008 at 18:40 Comment(10)
"There is no overkill when you are coding." I agree with this, which is why I find dynamic langs so wrong (though 100% of my paid work is in ruby right now).Biyearly
+1: I have had, maybe, 10 bugs caused by a mistake in overriding - the time required to find any one of them would easily have exceeded the time to type @Override on every one of my overriding methods. Besides, if @Override is some burdensome, you are probably over-using inheritance.Lianneliao
One very real downside is that you make the code harder to read by littering it with snails. Perhaps this is a fault of my IDE, but I have experienced this myself.Inquiline
@phyzome it can't be anywhere near as horrific as implementing a generic class--sometimes even using a generic class seems to make the code virtually unreadable. Since (as you say) annotations aren't generally interesting to programmers, perhaps eclipse can be told to hide them?Circumspection
@phyzome If you find the "Snails" cumbersome, you aren't using ANYWHERE NEAR enough comments. They should just be a single line above your method header which should be about as big as your method in most cases (a few lines) to provide decent hover text and javadocs. I guess I'm saying that the problem is not the Snails, it's your reading habits. Are all those parentheses in the code bothering you as well?Circumspection
I don't agree. On old versions of Java / Eclipse, the annotation will produce an error "The method ... of type ... must override a superclass method"Mindi
Yes, there is overkill in coding: when you write comments that just parrots what the code obviously does.Silvester
@Silvester I've heard that before but never seen it (Or it's been pretty minimal), most people simply use that phrase as an excuse to justify their lack of comments--but you may have worked with different people/groups with different standards. Also if the comments say in English what the code says in codish and most developers that follow you can save 3 seconds parsing that line, it's not a bad idea to spend the 5 seconds typing it.Circumspection
@Bill K: See refactormycode.com/codes/2025-numerical-methods-secant-method. Look at comments on lines where x0 and x1 are prepared for the next iteration.Silvester
@Silvester That is redundant but not at all harmful (Especially since they put it on the same line in that case)--whereas most of the time when someone complains about code like this it is to justify their lack of comments which can be more harmful. I have done stuff like this in cases where I will write out what I want in psuedocode first, then go and backfill with actual code. Works as an organizational tool sometimes, and is generally better if you leave the comments in but sometimes they turn out to be slightly redundant. If you are forming a lifetime habit, go with over-commenting.Circumspection
F
22

I always use the tag. It is a simple compile-time flag to catch little mistakes that I might make.

It will catch things like tostring() instead of toString()

The little things help in large projects.

Filar answered 18/9, 2008 at 16:50 Comment(0)
D
18

Using the @Override annotation acts as a compile-time safeguard against a common programming mistake. It will throw a compilation error if you have the annotation on a method you're not actually overriding the superclass method.

The most common case where this is useful is when you are changing a method in the base class to have a different parameter list. A method in a subclass that used to override the superclass method will no longer do so due the changed method signature. This can sometimes cause strange and unexpected behavior, especially when dealing with complex inheritance structures. The @Override annotation safeguards against this.

Dixon answered 18/9, 2008 at 16:54 Comment(2)
Best answer. Short and sweet. I wish you could explain though how the "safeguard" works.... nobody has explained this.Zebulon
It's simple to explain. If you make a mistake (either by changing the interface, abstract class or subclass, you'll get either a warning (such as in Eclipse) or a compile-time error telling you that your @Override isn't working. The actual error message will be dependent upon what was changed, but in Eclipse (for example) it's very clear very quickly that there's a problem: you'll see that little red zigzag underline, and a hover over the offending text will tell you what is wrong. I call that Good Value.Calamus
G
14

To take advantage from compiler checking you should always use Override annotation. But don’t forget that Java Compiler 1.5 will not allow this annotation when overriding interface methods. You just can use it to override class methods (abstract, or not).

Some IDEs, as Eclipse, even configured with Java 1.6 runtime or higher, they maintain compliance with Java 1.5 and don’t allow the use @override as described above. To avoid that behaviour you must go to: Project Properties ->Java Compiler -> Check “Enable Project Specific Settings” -> Choose “Compiler Compliance Level” = 6.0, or higher.

I like to use this annotation every time I am overriding a method independently, if the base is an interface, or class.

This helps you avoiding some typical errors, as when you are thinking that you are overriding an event handler and then you see nothing happening. Imagine you want to add an event listener to some UI component:

someUIComponent.addMouseListener(new MouseAdapter(){
  public void mouseEntered() {
     ...do something...
  }
});

The above code compiles and run, but if you move the mouse inside someUIComponent the “do something” code will note run, because actually you are not overriding the base method mouseEntered(MouseEvent ev). You just create a new parameter-less method mouseEntered(). Instead of that code, if you have used the @Override annotation you have seen a compile error and you have not been wasting time thinking why your event handler was not running.

Gudren answered 16/9, 2009 at 13:47 Comment(0)
S
8

Its best to use it for every method intended as an override, and Java 6+, every method intended as an implementation of an interface.

First, it catches misspellings like "hashcode()" instead of "hashCode()" at compile-time. It can be baffling to debug why the result of your method doesn't seem to match your code when the real cause is that your code is never invoked.

Also, if a superclass changes a method signature, overrides of the older signature can be "orphaned", left behind as confusing dead code. The @Override annotation will help you identify these orphans so that they can be modified to match the new signature.

Salcedo answered 18/9, 2008 at 18:0 Comment(0)
I
8

@Override on interface implementation is inconsistent since there is no such thing as "overriding an interface" in java.

@Override on interface implementation is useless since in practise it catches no bugs that the compilation wouldn't catch anyway. There is only one, far fetched scenario where override on implementers actually does something: If you implement an interface, and the interface REMOVES methods, you will be notified on compile time that you should remove the unused implementations. Notice that if the new version of the interface has NEW or CHANGED methods you'll obviously get a compile error anyways as you're not implementing the new stuff.

@Override on interface implementers should never have been permitted in 1.6, and with eclipse sadly choosing to auto-insert the annotations as default behavior, we get a lot of cluttered source files. When reading 1.6 code, you cannot see from the @Override annotation if a method actually overrides a method in the superclass or just implements an interface.

Using @Override when actually overriding a method in a superclass is fine.

Infective answered 2/9, 2009 at 14:44 Comment(1)
There are varying opinions on that point. See stackoverflow.com/questions/212614/… .Quechuan
N
7

If you find yourself overriding (non-abstract) methods very often, you probably want to take a look at your design. It is very useful when the compiler would not otherwise catch the error. For instance trying to override initValue() in ThreadLocal, which I have done.

Using @Override when implementing interface methods (1.6+ feature) seems a bit overkill for me. If you have loads of methods some of which override and some don't, that probably bad design again (and your editor will probably show which is which if you don't know).

Nineteenth answered 18/9, 2008 at 16:54 Comment(1)
Actually, it is also nice for overriden interface methods. If I e.g. remove an old, deprecated method from an interface, that method should be removed from all implementing classes as well - easy to spot those if they use @override.Linnea
L
7

@Override on interfaces actually are helpful, because you will get warnings if you change the interface.

Liger answered 18/9, 2008 at 17:37 Comment(0)
A
7

Another thing it does is it makes it more obvious when reading the code that it is changing the behavior of the parent class. Than can help in debugging.

Also, in Joshua Block's book Effective Java (2nd edition), item 36 gives more details on the benefits of the annotation.

Agamete answered 18/9, 2008 at 18:41 Comment(0)
L
6

Whenever a method overrides another method, or a method implements a signature in an interface.

The @Override annotation assures you that you did in fact override something. Without the annotation you risk a misspelling or a difference in parameter types and number.

Laing answered 18/9, 2008 at 16:50 Comment(1)
You can only use it to mark interface implementation in Java 1.6Sarrusophone
U
6

It makes absolutely no sense to use @Override when implementing an interface method. There's no advantage to using it in that case--the compiler will already catch your mistake, so it's just unnecessary clutter.

Unblock answered 27/1, 2010 at 1:53 Comment(2)
Using @Override on an interface will force you to notice when a method in the interface is removed.Eulogium
@Alex: Removing methods in an interface is a breaking change, like adding them. Once an interface is published, it's effectively locked in unless you have complete control over all the code using it.Lianneliao
C
5

I use it every time. It's more information that I can use to quickly figure out what is going on when I revisit the code in a year and I've forgotten what I was thinking the first time.

Clayborne answered 18/9, 2008 at 16:49 Comment(0)
C
5

The best practive is to always use it (or have the IDE fill them for you)

@Override usefulness is to detect changes in parent classes which has not been reported down the hierarchy. Without it, you can change a method signature and forget to alter its overrides, with @Override, the compiler will catch it for you.

That kind of safety net is always good to have.

Cathiecathleen answered 18/9, 2008 at 16:54 Comment(1)
So, if you change the parent method, and your not using @Override in the child class's method, will the compile say anything or remain silent? Will the use of "Override" give you more information, and if so, what?Zebulon
T
5

I use it everywhere. On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.

I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.

Tiki answered 18/9, 2008 at 17:49 Comment(0)
C
5
  • Used only on method declarations.
  • Indicates that the annotated method declaration overrides a declaration in supertype.

If used consistently, it protects you from a large class of nefarious bugs.

Use @Override annotation to avoid these bugs: (Spot the bug in the following code:)

public class Bigram {
    private final char first;
    private final char second;
    public Bigram(char first, char second) {
        this.first  = first;
        this.second = second;
    }
    public boolean equals(Bigram b) {
        return b.first == first && b.second == second;
    }
    public int hashCode() {
        return 31 * first + second;
    }

    public static void main(String[] args) {
        Set<Bigram> s = new HashSet<Bigram>();
        for (int i = 0; i < 10; i++)
            for (char ch = 'a'; ch <= 'z'; ch++)
                s.add(new Bigram(ch, ch));
        System.out.println(s.size());
    }
}

source: Effective Java

Cowshed answered 2/10, 2009 at 16:45 Comment(4)
I don't know what the operator precedence rules are in Java, but your equals method is screaming BUUUUUUUUUUUG! I'd write (b.first == first) && (b.second == second), even if && had lower precedence than ==.Pudency
Did you know that your link shows a 'you must subscribe' message covering the useful part of that page?Renshaw
@Adriano: Sorry dude!! Am helpless!! When I wrote the 'answer', it was available. No worries..buy the book. It's worth to have it!!Cowshed
The equals method does not override: The original Object::equals is boolean equals(Object), while the overridden equals is boolean equals(Bigram), which has a different method signature, which does not override. Adding @Override to the equals will detect this blunder.Evangelicalism
N
3

Be careful when you use Override, because you can't do reverse engineer in starUML afterwards; make the uml first.

Nostalgia answered 10/5, 2010 at 16:30 Comment(0)
A
2

It seems that the wisdom here is changing. Today I installed IntelliJ IDEA 9 and noticed that its "missing @Override inspection" now catches not just implemented abstract methods, but implemented interface methods as well. In my employer's code base and in my own projects, I've long had the habit to only use @Override for the former -- implemented abstract methods. However, rethinking the habit, the merit of using the annotations in both cases becomes clear. Despite being more verbose, it does protect against the fragile base class problem (not as grave as C++-related examples) where the interface method name changes, orphaning the would-be implementing method in a derived class.

Of course, this scenario is mostly hyperbole; the derived class would no longer compile, now lacking an implementation of the renamed interface method, and today one would likely use a Rename Method refactoring operation to address the entire code base en masse.

Given that IDEA's inspection is not configurable to ignore implemented interface methods, today I'll change both my habit and my team's code review criteria.

Anathematize answered 7/11, 2009 at 0:35 Comment(0)
W
2

The annotation @Override is used for helping to check whether the developer what to override the correct method in the parent class or interface. When the name of super's methods changing, the compiler can notify that case, which is only for keep consistency with the super and the subclass.

BTW, if we didn't announce the annotation @Override in the subclass, but we do override some methods of the super, then the function can work as that one with the @Override. But this method can not notify the developer when the super's method was changed. Because it did not know the developer's purpose -- override super's method or define a new method?

So when we want to override that method to make use of the Polymorphism, we have better to add @Override above the method.

Womanhater answered 25/11, 2011 at 8:31 Comment(0)
J
1

I use it as much as can to identify when a method is being overriden. If you look at the Scala programming language, they also have an override keyword. I find it useful.

Jaclyn answered 29/3, 2011 at 15:34 Comment(0)
F
0

It does allow you (well, the compiler) to catch when you've used the wrong spelling on a method name you are overriding.

Fusty answered 18/9, 2008 at 16:51 Comment(0)
A
0

Simple–when you want to override a method present in your superclass, use @Override annotation to make a correct override. The compiler will warn you if you don't override it correctly.

Absently answered 3/12, 2009 at 21:43 Comment(0)
W
0

Override annotation is used to take advantage of the compiler, for checking whether you actually are overriding a method from parent class. It is used to notify if you make any mistake like mistake of misspelling a method name, mistake of not correctly matching the parameters

Wolters answered 18/5, 2010 at 6:6 Comment(0)
U
0

i think it's best to code the @override whenever allowed. it helps for coding. however, to be noted, for ecipse Helios, either sdk 5 or 6, the @override annotation for implemented interface methods is allowed. as for Galileo, either 5 or 6, @override annotation is not allowed.

Unread answered 3/12, 2010 at 5:55 Comment(0)
C
0

Annotations do provide meta data about the code to the Compiler and the annotation @Override is used in case of inheritance when we are overriding any method of base class. It just tells the compiler that you are overriding method. It can avoide some kinds common mistakes we can do like not following the proper signature of the method or mispelling in name of the method etc. So its a good practice to use @Override annotation.

Consolidation answered 22/11, 2011 at 6:40 Comment(0)
S
0

For me the @Override ensures me I have the signature of the method correct. If I put in the annotation and the method is not correctly spelled, then the compiler complains letting me know something is wrong.

Scopula answered 16/1, 2012 at 3:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.