title: When to use @Override in java
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why">When do you use Java&rsquo;s @Override annotation and why?</a>  </p>
  </blockquote>
  
  <p>From the javadoc for the @Override annotation:</p>
  
  <blockquote>
    <p>Indicates that a method declaration is
    intended to override a method 
    declaration in a superclass. If a
    method is annotated with this 
    annotation type but does not override
    a superclass method, compilers are
    required to generate an error message.</p>
  </blockquote>
  
  <p>I've tended to use the @Override annotation in testing, when I want to test a specific method of a type and replace the behaviour of some other method called by my test subject. One of my colleagues is firmly of the opinion that this is not a valid use but is not sure why. Can anyone suggest why it is to be avoided?</p>
  
  <p>I've added an example below to illustrate my usage.</p>
  
  <p>For the test subject Foo:</p>
  
  <pre><code>public class Foo {
      /**
       * params set elsewhere
       */
      private Map&lt;String, String&gt; params;
  
      public String doExecute(Map&lt;String, String&gt; params) {
          // TODO Auto-generated method stub
          return null;
      }
  
      public String execute() {
          return doExecute(params);
      }
  }
  </code></pre>
  
  <p>I would define a test like this:</p>
  
  <pre><code>public void testDoExecute() {
      final Map&lt;String, String&gt; expectedParams = new HashMap&lt;String, String&gt;();
      final String expectedResult= "expectedResult";
      Foo foo = new Foo() {
          @Override
          public String doExecute(Map&lt;String, String&gt; params) {
              assertEquals(expectedParams, params);
              return expectedResult;
          }
      };
  
      assertEquals(expectedResult, foo.execute());
  }
  </code></pre>
  
  <p>Then if my doExecute() signature changes I'll get a compile error on my test, rather than a confusing execution failure.</p>