Understanding OOP Concepts: Method Overriding

In this article, we’re going to learn the method overriding concept in OOP. Let’s get started:

Table of Contents

  1. What is Method Overloading?
  2. Rules of Overloading
  3. The Super Keyword

What is Method Overloading?

Method Overloading is a technique that allows a subclass to declare the same method which is already present in the parent class. This technique is an example of runtime polymorphism or dynamic method dispatch.

An example:

class Animal {
   public void displayInfo() {
      System.out.println("I am an animal");
   }
}

class Cat extends Animal {
   @override
   public void displayInfo() {
      System.out.println("I am a cat.");
   }
}

class Main {
   public static void main(String[] args) {
      Cat c1 = new Cat();
      c1.displayInfo();
   }
}

Rules of Overloading

There are some rules of method overriding. I’m going to mention some of the rules in short.

Rules 1: The parent class and the child class must have the same method name.

Rules 2: The parent class and the child class must have the same parameter & return type.

Rules 3: The static & final methods cannot be overridden. In Java, private methods cannot be overridden too.

Rules 4: Abstract method must be overridden in child class.

Rules 5: Constructor cannot be the same for a parent class and a subclass.

The Super Keyword

By using the super keyword, we can access the parent class methods from the child class.

Let’s see an example:

class Animal {
   public void displayInfo() {
      System.out.println("I am an animal");
   }
}

class Cat extends Animal {
   public void displayInfo() {
      super.displayInfo();
      System.out.println("I am a cat");
   }
}

class Main {
   public static void main(String[] args) {
      Cat c1 = new Cat();
      c1.displayInfo();
   }
}

The output:

I am an animal
I am a cat

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.