8

Possible Duplicate:
When do you use Java's @Override annotation and why?

Newbie question - I'm writing my first Android app (its my 2nd Java app). I noticed that in examples the onCreate() method has the @Override annotation, but I haven't used that annotation and it seems to work fine.

Is it just good practice to use the @Override annotation or am I setting myself up for problems. What about the other inherited methods - onPause etc?

Community
  • 1
  • 1
Yoav
  • 2,077
  • 6
  • 27
  • 48

4 Answers4

13

The @Override annotation allows the compiler to ensure you're actually overriding a method or implementing an interface method (Java 6+). This can avoid one class of simple errors, like screwing up a method signature and not actually overriding what you think you are.

It's not mandatory, but it's a good idea, and is free help from the compiler.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
12

It's only good practice, which

  • helps developers see which methods are overriden
  • lets the compiler check that the signature is compliant with the overriden method
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • +1 for the second point especially. But don't rely on it for the first point, as it's not mandatory: any good IDE (Eclipse, IntelliJ) will show you overridden methods independently of the @Override annotation. – Guillaume Dec 20 '11 at 15:54
3

If you are really a newbie than you have to know about compiletime (when you compile your source code) and runtime (when you run your compiled class).

Suppose, you need to override some method, but while overriding the method you gave wrong singnature (different than the original one).

Now, in such a case, if have used that @Override annotation then the compiler will tell that you are actually not overriding the method even though you are thinking so.

But, if you don't use that annotation than it will compile and the end result is some bug in the runtime.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
1

I think that it is not just a good practice but a very good practice. Additionally to kind of reminder to programmer it also helps you not to leave died code in your program and often avoid stupid bugs.

If for example you override method foo() of your base class and then remove this method from base class. If you do not use @Override annotation there is a chance that code that cannot be accessed any more still exists in sub-classes. But if you do use @Override you get compilation error that signals you that you have to do something with the code.

AlexR
  • 114,158
  • 16
  • 130
  • 208