Java Reference
In-Depth Information
4.2.3 The @Override annotation in J2SE 5.0
One of the annotations available with the addition of the metadata facility in Java
Version 5.0 (see Chapter 1) greatly reduces the chance of accidentally overloading
when you really want to override. The @Override annotation tells the compiler
that you intend to override a method from a superclass. If you don't get the
parameter list quite right so that you're really overloading the method name, the
compiler emits a compile-time error. This annotation is used as follows:
public class Parent {
int i = 0;
void doSomething (int k) {
i = k;
}
}
class Child extends Parent {
@Override
void doSomething (long k) {
i = 2*k;
}
}
The metadata facility in Java 5.0 supports simple and complex annotation types,
which are closely related to Java interfaces (discussed in Section 4.5). Some anno-
tation types define member methods and member variables and require parameters
when used. However, the @Override annotation is just a marker interface (see
Section 4.5.3). It has no members, and thus accepts no parameters when used,
as shown above. It must appear on a line by itself and indicates that the method
name on the next line should override a method from a superclass. If the method
signature on the next line isn't really an overriding signature, then the compiler
complains as follows:
Parent.java:10: method does not override a method from its
superclass
@Override
1 error
By using @Override each time you intend to override a method from a super-
class, you are safe from accidentally overloading instead of overriding.
 
Search WWH ::




Custom Search