DEV Community

Cover image for Java Method overriding
Dilanka Rathnasiri
Dilanka Rathnasiri

Posted on

Java Method overriding

cover image: Photo by Erik Witsoe on Unsplash

We are discussing Java Method overriding in this article with examples.

What is Java Method Overriding?

There is a child class. Let’s take it as class A. Its parent class is B. All methods in B are inherited from B to A. A has a method c. It has the same signature (method name and parameter types) as a method in B. Method c in A has its own implementation specific to A. This is called method overriding.

Why do we need Java Method Overriding?

  1. When we want specific implementation for a function in the child class

  2. Achieve Runtime Polymorphism in Java

  3. When we want to have customized implementation of java native methods

Run Time Polymorphism

In Run Time Polymorphism, Java Virtual Machine determines which methods to call at the run time. A child class has its own specific implementation for a method that already exists in the parent class.

Example 1

First, we see a simple example of how to do Java Method overriding.

public class Car {
    public void running() {
        System.out.println("Car is running");
    }
}

public class Benz extends Car{
}

public class BMW extends Car{
    @Override
    public void running() {
        System.out.println("BMW car is running");
    }
}

public class Example1 {
    public static void main( String[] args ) {
        Car car1 = new Benz();
        Car car2 = new BMW();

        car1.running();
        car2.running();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Car is running
BMW car is running
Enter fullscreen mode Exit fullscreen mode

In this example, we have overridden running method in BMW class.

Example 2

Also, we can use Java method overriding for customizing the implementation of java native methods.

Let’s see how we implement a simple case-insensitive Java HashMap.

public class Student {
    private String name;
    private int grade;

    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public int getGrade() {
        return grade;
    }
}

import java.util.HashMap;
import java.util.Map;

public class Example2 {
    public static void main(String[] args) {
        Student student1 = new Student("Kamal", 10);
        Student student2 = new Student("Nimal", 7);

        Map<String, Student> studentOverrideMap = new HashMap<>() {
            @Override
            public Student put(String key, Student value) {
                return super.put(key.toLowerCase(), value);
            }

            @Override
            public Student get(Object key) {
                return super.get(key.toString().toLowerCase());
            }

            @Override
            public boolean containsKey(Object key) {
                return super.containsKey(key.toString().toLowerCase());
            }
        };

        studentOverrideMap.put("Kamal", student1);
        studentOverrideMap.put("Nimal", student2);

        System.out.println("Student1 name:" + studentOverrideMap.get("KAMAL").getName() + " grade:" + studentOverrideMap.get("KAMAL").getGrade());
        System.out.println("Student2 name:" + studentOverrideMap.get("NIMAL").getName() + " grade:" + studentOverrideMap.get("NIMAL").getGrade());
        System.out.println("KAMAL is in map: " + studentOverrideMap.containsKey("KAMAL"));
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Student1 name:Kamal grade:10
Student2 name:Nimal grade:7
KAMAL is in map: true
Enter fullscreen mode Exit fullscreen mode

In this example, we have overridden put, get, and containsKey methods in Java HashMap. In put method, we have converted the HashMap key to lowercase before we add an element to the HashMap. In get method, we have converted the HashMap key to lowercase before getting the object. In containsKey method, we have converted the HashMap key to lowercase before searching for the key.

The situations when we cannot use Java Method Overriding

  1. We cannot use Java Method Overriding for static methods

  2. We cannot use Java Method Overriding for final methods

Summary

A child class has its own specific implementation for a method that already exists in the parent class. This is called Java Method Overriding. We can use Java Method Overriding for having a specific implementation for a function in the child class, achieving Runtime Polymorphism in Java, and having a customized implementation of java native methods. We cannot use Java Method Overriding for final or static methods.

Thank you for reading!

References

  1. Overriding in Java - GeeksforGeeks
  2. What is Method Overriding in Java? Uses, Examples & Everything You Should Know
  3. Difference between Compile-time and Run-time Polymorphism in Java - GeeksforGeeks

Top comments (0)