What does @Override comment means in Java

Learn what @Override comment in java does in your code.

@Override sentence uses comment syntax. This sentence lets to the Java compiler know that you want to override an existing method of a parent class (overwrite how a function works in this class while it exists in the parent class).

For example, the following class

public class Base {
    public void saySomething() {
        System.out.println("Hi, I'm a base class");
    }
}

public class Child extends Base {
    @Override
    public void saySomething() {
        System.out.println("Hi, I'm a child class");
    }
}

Copy snippet

In this case we are overriding what saySomething method does in the Child class, therefore if you use it somewhere, for example:

public static void main(String [] args) {
    Base obj = new Child();
    obj.saySomething();
}

Copy snippet

The expected output will be : “Hi, I’m a child class”. Is important to know that @Override only works for public and protected functions.

In Java 6, it also mean you are implementing a method from an interface.

However that’s not the only function of @Override, it will be a potential help to quickly identify typos or API changes in the methods. Analize the following example:

public int multiplyinteger()

public int multiplyInteger()

Copy snippet

Do you find something weird ? Nope ? (Look for uppercases in some of the methods). That’s right, if the method is named multiplyinteger but you call it multiplyInteger, you’ll never know what’s going on because indeed, nothing will happen.

This function will be not executed because it simply doesn’t exists, however if you use @Override you’ll get a clear warning or error when trying to compile. Adding @Override to a method makes it clear that you are overriding the method and make sure that you really are overriding a method that exists.

5 People reacted on this

  1. I went over this web site and I believe you have a lot of great info , saved to fav (:.

  2. The the next time I just read a weblog, I really hope that this doesnt disappoint me about brussels. Get real, Yes, it was my replacement for read, but When i thought youd have something intriguing to talk about. All I hear can be a number of whining about something you could fix if you ever werent too busy looking for attention.

Leave a Comment