Uncategorized

@Override

By November 27, 2010 No Comments

It’s a simple thing that should probably be used more often.

When overriding a method in Java, use the @Override keyword one line above the new method you are creating. You certainly don’t have to, but this way the compiler will be sure to remind you if you make any changes that make your overridden and overriding methods incompatible. 

What could happen? Let’s look at an example.

public class Mammal
{
     public void printType()
     {
         System.out.println(“I’m a mammal!”);
    }

public class Tiger extends Mammal
{
     public void printType()
     {
         System.out.println(“I’m a mammal and a tiger!”);
     } 

So now let’s say I created a new tiger and I call tiger.printType()
Clearly, it will print “I’m a mammal and a tiger!”
But what happens if I make a change when defining printType() in my Tiger class? (This could easily happen if I decide to change the method’s name or I if I make a spelling error). For example,

public class Tiger extends Mammal
{
     public void printTpe()
     {
          System.out.println(“I’m a mammal and a tiger!”);
     } 

Now when I call tiger.printType(), it will print “I’m a mammal!” which is clearly not what I intended. 

What if I had used the @Override keyword?

public class Tiger extends Mammal
{
     @Override
     public void printTpe()
     {
          System.out.println(“I’m a mammal and a tiger!”);
     } 

In this case, the compiler would’ve let me know that there is no such method to be overridden in the parent class, and I would have known to fix it :)

Leave a Reply