XNSIO
  About   Slides   Home  

 
Managed Chaos
Naresh Jain's Random Thoughts on Software Development and Adventure Sports
     
`
 
RSS Feed
Recent Thoughts
Tags
Recent Comments

@Override annotation, I’m looking at you

Being out of touch with Java coding and moving between Java 5 and 6 can be a great way to assume yourself. Couple of days back I stumbled upon a fairly well know Java 5 feature, @Override annotation. Annotations were introduced in Java 5. According to the JavaDoc

public @interface Override

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.

One would read this and think the following code should work perfectly fine:

1
2
3
interface I {
  void m1();
}
1
class C implements I {
1
2
3
4
  @Override
  public void m1() {
  }
}

But guess what? In Java 5, the compiler gives the following error: “The method m1() of type C must override a superclass method”

The same exact code works perfectly fine on Java 6. You go back and read the Javadocs again and you can’t seem to find a fault. But it turns out that in Java 5, @Override annotation only applied to methods overridden from a superclass and not from Interfaces. (So if you implement a method from an Interface, @Override annotation cannot be applied in Java 5).
This was apparently a bug in Java 5, which was fixed in Java 6. Here is the bug report : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6399361
This is great, but there is no mention on public JDK 6 JavaDocs nor in the release notes.
Eclipse IDE 3.3.1.1 recognizes the new feature and add the @Override annotation auto-magically every time I override a method or implement an interface method. Pretty cool! Unfortunately for all you Intelij fans, there is an open bug still waiting to be fixed.

    Licensed under
Creative Commons License