Saturday, September 1, 2012

Annotations in Java

Annotation in java

========
What are the advantages of Annotation?
========

As we are aware that every class is subclass of object. AnnotationOverrideTest ca object class has two overridden methods. But Object class does not have toStirng123() method. Here compiler will give an error. Which will save developer time as well as errors caused by human ignorance.
public class AnnotationOverrideTest {
  
   @Override public String toString() {
      return "Override the toString() of the superclass";
   }
  
   // Compilation Error because superclass Object does not have this method
   @Override public String toString123() {
      return "Override the toString123() of the superclass";
   }
}

If you look at below code, developer is trying to do some action on window close event. Program will easily compile and run, but will not work as expected on closing event.  If you look carefully method name is not spelled correctly. This could have been avoided if @override annotation is been used. Compile will give compile time error if you do this kind of mistake. This can save lots of debugging time.
import java.awt.*;
import java.awt.event.*;
public class AnnotationOverrideDemo extends Frame {
   public AnnotationOverrideDemo() {
      this.addWindowListener(new WindowAdapter() {
         public void windowclosing(WindowEvent e) {
            System.exit(0);
         }
      });
      setSize(200, 100);
      setTitle("Annotation Override Demo");
      setVisible(true);
   }
   public static void main(String[] args) { new AnnotationOverrideDemo(); }
}

No comments:

Post a Comment