Question about @Override annotation
I开发者_JAVA百科m new to android development. I would like to know why do we have to precede every overriden method with @Override annotation in android ?. In regular java this is not a requirement.
Please Help Thanks
The @Override
notation is used so the compiler can warn you if the method-signature isn't the same as the super class method-signature. It can warn you about tedious bugs, and it is not required in Android, but it is good practice both in "normal" Java programming and Android Programming.
If you in "normal" Java had misspelled the toString-method e.g. public String toString(int n) {...}
and you had the @Override
the compiler will warn you because you are not overriding a method in the superclass.
It's a best practice and it's safe. Assume that you have a class:
public class MyClass {
...
...
public void doSomething() {
...
...
}
}
Now assume you extend it:
public class MyExtendedClass extends MyClass {
...
...
public void doSomthing() {
...
}
}
This code will compile, but you'll have problems because you actually haven't overridden the method! Note the misspelling. Now if you annotate it with @Override
:
public class MyExtendedClass extends MyClass {
...
...
@Override
public void doSomthing() {
...
}
}
The java compiler will complain because you are trying to override a method that does not exist in the base class. Essentially using @Override
lets you catch problems like these at compile-time.
This is especially useful when you refactor. If you change a method signature or a name, but don't have the @Override
annotation, some methods may slip-by leading to hard-to-find bugs (of course, with modern IDE's a lot of this pain is mitigated, but still). If you judiciously use the @Override
annotation, you will now get compiler errors and so you will be able to fix the method signatures in your derived classes.
Because it is a good programming practice. Overriding a method without using @Override
makes for a potentially difficult-to-find bug in the future if the base method's signature changes (I've wasted hours on these sorts of bugs before).
精彩评论