Java Overriding

java

In Java, method overriding is a feature that allows a subclass to provide a new implementation for a method that is already defined in the superclass. Method overriding is an example of polymorphism, which is the ability of a single entity (such as a method or an object) to have multiple forms.

To override a method in Java, you must first create a subclass that extends the superclass that contains the method you want to override. Then, you can provide a new implementation for the method in the subclass, using the same method signature (name and parameter list) as the original method in the superclass.

Here’s an example of method overriding in Java:

class Animal {
  public void makeSound() {
    System.out.println("Some generic animal sound");
  }
}

class Cat extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Meow");
  }
}

In this example, the Cat class extends the Animal class and overrides the makeSound() method. When the makeSound() method is called on a Cat object, the version of the method in the Cat class will be executed, rather than the version in the Animal class.

There are a few rules to follow when overriding a method in Java:

  • The method in the subclass must have the same signature as the method in the superclass.
  • The method in the subclass must have the same return type (or a subclass of the return type) as the method in the superclass.
  • The method in the subclass must have the @Override annotation, which tells the compiler to check that the method is actually overriding a method in the superclass.