use of @override annotation in java - why ?

The @Override annotation is your compile‑time guardian—it tells the compiler “I intend to override a parent method.” If there’s no matching superclass method, the compiler throws an error. 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 spot the bug?

The equals method here doesn’t override—it overloads. Object.equals expects an Object, but our version takes a MyCharacterSet. The different parameter type means it’s a completely new method, not an override. Adding @Override would have caught this at compile time.

Fix: change the signature to properly override Object.equals:

 @Override
 public boolean equals(Object arg0) {
  MyCharacterSet b = (MyCharacterSet) arg0;
  return b.first == first && b.second == second;
 }

No comments :

Post a Comment

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