Thursday 12 March 2020

@Override annotation in Java? Best practices

Hi, Today we will see @Override annotation in Java is used to indicate that a method in a subclass is intended to override a method in its superclass. Using this annotation is a coding best practice because it helps to catch errors early in the development process by ensuring that the overridden method has the correct method signature, including the method name, return type, and parameter types.

Here is an example:

Suppose we have a superclass Animal with a method makeSound(), and we want to create a subclass Cat that overrides this method to make a different sound. We can define the Cat class like this:

public class Cat extends Animal {

    @Override

    public void makeSound() {

        System.out.println("Meow");

    }

}

Read more »

Labels: , , , ,