sHome : Course Map : Chapter 4 : Java : Supplements :
The @Override Annontation in J2SE5.0
JavaTech
Course Map
Chapter 4

Introduction
Inheritance
  Demo 1
Overriding
  Demo 2a
  Demo 2b
this,super
MoreConstructors
  Demo 3
Abstraction
Interface 
  Demo 4
Casting References
MoreAboutArrays
Object class
Class Summary
Exercises

    Supplements
Override/Overload
Annotation-J2SE5.0
Java Security
Class Loading
Class Verifier
SecurityManager
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

One of the annotations available with the addition of the metadata facility in Java Version 5.0 (see Chapter 1: Java and Chapter 1 Java: Supplement), 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. Some annotation types define member methods and member variables and require parameters when used. However, the @Override annotation is just a marker interface. 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 superclass, you are safe from accidentally overloading instead of overriding.

References & Web Resources

  1. Calvin Austin, J2SE 5.0 in a Nutshell, Sun Developer Network, May 2004.
  2. Java Programming Language - Enhancements for JDK 5
  3. Annotations - Java Programming Language Guide for JDK 5.

 

Latest update: Oct. 20, 2004

            Tech
MoreComplexClass
ImprovedHistogram
JavaRandomNums
Vectors & Matrices
Exercises

           Physics
Runge-Kutta 2nd
  Demo 1
Runge-Kutta 4th
  Demo 2
BoundaryVal.Prob
Shooting Method
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.