use of @override annotation in java - why ?

The @override annotation  is most useful as a compile-time reminder that the intention of the method is to override a parent method. See this example:

import java.util.HashSet;
import java.util.Set;
/**
 * Override_Annotation_Usage_Example, from  Effective Java
 */
public class MyCharacterSet {
 private final char first;
 private final char second;
 public MyCharacterSet(char first, char second) {
  this.first = first;
  this.second = second;
 }
 public boolean equals(MyCharacterSet b) {
  return b.first == first && b.second == second;
 }
 public int hashCode() {
  return 31 * first + second;
 }

 public static void main(String[] args) {
  Set s = new HashSet();

  for (int i = 0; i < 10; i++)
   for (char ch = 'a'; ch <= 'z'; ch++)
    s.add(new MyCharacterSet(ch, ch));

  System.out.println(s.size());
 }
}


Can you notice the error in above code ?

The equals method does not override: The original Object::equals is boolean equals(Object), while the overridden equals is boolean equals(MyCharacterSet ), which has a different method signature, which does not override. Adding @Override to the equals will detect this blunder.

Correction : change the method signature as :

 @Override
 public boolean equals(Object arg0) {
  MyCharacterSet b = (MyCharacterSet) arg0;
  return b.first == first && b.second == second;
 }
You should use the @Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...