Method Overriding In Java With Example

Introduction 

Method overriding is a fundamental concept in object-oriented programming (OOP) languages, including Java. It allows a subclass to provide its own implementation of a method inherited from its superclass. In this article, we will delve into what method overriding is, why it is essential, provide three examples with code, and highlight the key differences between method overloading and method overriding through a tabular comparison.

What Is Method Overriding? 

Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its superclass. The overriding method has the same name, return type, and parameters as the method in the superclass. It enables polymorphism, allowing objects of different classes to be treated interchangeably based on their shared superclass.

Why Is Method Overriding Important?

 Method overriding serves several purposes and benefits:

  • Polymorphism: By overriding methods, you can achieve polymorphism, where different objects can respond differently to the same methods invocation. This flexibility allows you to write more general and reusable code.
  • Enhancing Behavior: Method overriding enables you to modify or enhance the behavior of inherited methods in the subclass. This allows you to tailor the behavior of the method to the specific needs of the subclass, adding new functionality or customizing existing behavior.
  • Code Extensibility: Method overriding facilitates code extensibility by providing a way to build upon existing functionality. You can inherit and reuse methods from the superclass while adding specific behaviors in the subclass, making your code more modular and maintainable.

Examples of Method Overriding:

  • Animal Class Hierarchy: In this example, we define an Animal class with a method makeSound() and create subclasses Dog and Cat that override the makeSound() method with their specific implementations.
class Animal {
    public void makeSound() {
        System.out.println("Animal makes a sound.");
    }
}

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

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

Usage:

Animal animal = new Animal();
animal.makeSound();    // Output: Animal makes a sound.

Animal dog = new Dog();
dog.makeSound();       // Output: Dog barks.

Animal cat = new Cat();
cat.makeSound();       // Output: Cat meows.
  • Shape Class Hierarchy: In this example, we create a Shape superclass with a method calculateArea() and subclasses Rectangle and Circle that override the calculateArea() method with their specific implementations.
abstract class Shape {
    public abstract double calculateArea();
}

class Rectangle extends Shape {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public double calculateArea() {
        return length * width;
    }
}

class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

Usage:

Shape rectangle = new Rectangle(5, 3);
System.out.println("Rectangle Area: " + rectangle.calculateArea());   // Output: Rectangle Area: 15.0

Shape circle = new Circle(2.5);
System.out.println("Circle Area: " + circle.calculateArea());         // Output: Circle Area: 19.634954084936208
  • Method Overriding with Exception: In this example, we demonstrate method overriding when the overridden methods throws an exception. The subclass can either throw the same exception or its subclass exception.
class Superclass {
    public void methodWithException() throws IOException {
        // Method implementation
    }
}

class Subclass extends Superclass {
    @Override
    public void methodWithException() throws FileNotFoundException {
        // Method implementation
    }
}

Differences between Method Overloading and Method Overriding:

Method OverloadingMethod Overriding
DefinitionMultiple methods with the same name but different parametersA subclass provides its own implementation of a method inherited from its superclass
PurposeTo provide variations of a method based on different parametersTo modify or extend the behavior of an inherited method
SignatureDiffers in terms of the number, types, or order of parametersRemains the same as the overridden method (same name, return type, and parameters)
RelationshipSame classSuperclass-subclass relationship
DeterminationCompile-timeRun-time (based on the actual type of the object at runtime)
ExamplesAddition of integers and floating-point numbersOverriding toString() method in Object class, customizing behavior in subclasses like Dog or Cat
AnnotationNot necessary, as it is resolved during compilationOptional @Override annotation (provides a compile-time check for correct overriding, ensures method exists in the superclass)

Conclusion

Method overriding is a powerful feature in Java that allows subclasses to provide their own implementation of methods inherited from superclasses. It promotes code extensibility, polymorphism, and customization, enabling more flexible and reusable code. By understanding the differences between method overloading and method overriding, you can leverage these concepts to design robust and modular Java applications.

Remember, methods overriding is determined at runtime, based on the actual type of the object, while methods overloading is resolved at compile-time based on the method’s signature.

So embrace the flexibility of method overriding, use it to create more specialized and tailored behavior, and unlock the full potential of OOP in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *