Interview Questions, Answers and Tutorials

Overriding methods

Overriding methods

Hey there, future coding masterminds! Today, we’re going to embark on an exciting journey into the world of Java programming. Buckle up and get ready to dive into the fascinating concept of “overriding methods.”

What is Overriding?

Imagine you have a robot that can perform different tasks, like dancing or singing. Now, let’s say you want to upgrade your robot and make it dance even better. Instead of building a new robot from scratch, you decide to take the existing dancing function and improve it. This is similar to what we do in programming when we talk about “overriding.”

In Java, classes can have methods, which are like the tasks our robot can perform. When you want to change or improve the behavior of a method in a subclass (a new and improved version of a class), you can use a concept called method overriding.

Java Code Example:

Let’s create a simple example to illustrate method overriding. Imagine we have a class called Robot with a method called performTask:

class Robot {
void performTask() {
System.out.println(“Performing a generic task.”);
}
}

Now, let’s create a subclass called DancingRobot that extends the Robot class. We want our dancing robot to have a unique way of performing tasks, so we’ll override the performTask method:

class DancingRobot extends Robot {
    @Override
    void performTask() {
        System.out.println("Dancing to the rhythm!");
    }
}

Explanation:

  1. Inheritance: The DancingRobot class extends the Robot class, which means it inherits the performTask method.
  2. @Override Annotation: The @Override annotation is like a label that tells Java we are intentionally changing the behavior of the method. It helps catch errors if we accidentally don’t override the method correctly.
  3. New Implementation: The overridden performTask method in the DancingRobot class provides a new implementation. Now, when we call performTask on a DancingRobot object, it will dance instead of performing the generic task.

Usage:

public class Main {
    public static void main(String[] args) {
        Robot genericRobot = new Robot();
        DancingRobot dancingRobot = new DancingRobot();

        genericRobot.performTask(); // Output: Performing a generic task.
        dancingRobot.performTask(); // Output: Dancing to the rhythm!
    }
}

Congratulations, young coders! You’ve just dipped your toes into the awesome world of method overriding in Java. Just remember, when you want to improve or customize a method in a subclass, overriding is the way to go. Keep coding and exploring, and who knows, you might create the next generation of dancing robots in the digital world!