Introducing Java Method Overriding And Super Keyword


Method Overriding

Changing the Body of a Method from a Super Class to a Sub Class is "Method Overriding".

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

  • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

In Overriding, only the Method related to the Object is always executed.


Super Keyword

The "Super Keyword" is used to call the constructor of the Super Class from a Sub Class.

The Super Keyword refers to superclass (parent) objects.

It is used to call superclass methods, and to access the superclass constructor.

The most common use of the Super Keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

class Animal { // Superclass (parent)
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Dog extends Animal { // Subclass (child)
  public void animalSound() {
    super.animalSound(); // Call the superclass method
    System.out.println("The dog says: bow wow");
  }
}

public class Main {
  public static void main(String args[]) {
    Animal myDog = new Dog(); // Create a Dog object
    myDog.animalSound(); // Call the method on the Dog object
  }
}
GitHub Projects


Comments

Popular posts from this blog

Introducing Java Encapsulation Concept

Introducing Java Interfaces Concept