Home page

Saturday, July 8, 2023

Method overriding in JAVA

Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Method overriding is used to achieve polymorphism, where a subclass can define its behavior while maintaining a common interface. Here's an overview of when and how to use method overriding in Java:

Purpose:

Modify Behavior: Method overriding allows a subclass to modify or extend the behavior of a method inherited from its superclass.

Polymorphism: Method overriding enables polymorphism, where an object of the subclass can be treated as an object of the superclass, providing flexibility and code reuse.

Follows the "IS-A" Relationship: Method overriding is used when a subclass "IS-A" type of its superclass, indicating a specialization or refinement of the superclass behavior.

How to use:

Create a subclass that extends the superclass containing the method to be overridden.

Define a method in the subclass with the same signature (name, return type, and parameters) as the method in the superclass.

Add the @Override annotation to ensure that the method is indeed intended to override a superclass method. While not mandatory, it helps prevent accidental mistakes.

The subclass method must have the same or more permissive access modifier as the superclass method.

Example:

class Shape {

    public void draw() {

        System.out.println("Drawing a shape");

    }

}

class Circle extends Shape {

    @Override

    public void draw() {

        System.out.println("Drawing a circle");

    }

}

// Using method overriding

Shape shape = new Circle(); // Polymorphic assignment

shape.draw(); // Output: "Drawing a circle"

In the above example, the Shape class has a method called draw(), and the Circle class extends the Shape class. The Circle class overrides the draw() method with its specific implementation. When we create an object of the Circle class and invoke the draw() method through the Shape reference, the overridden method in the Circle class is executed, demonstrating polymorphism.

Remember the following points when using method overriding:

The method in the subclass must have the same method signature (name, return type, and parameters) as the method in the superclass.
The subclass method must be declared with the @Override annotation to indicate that it is intended to override a superclass method.
The subclass method can have a more permissive access modifier (e.g., public) but not a more restrictive one (e.g., private).
Method overriding is useful when you want to provide a specialized implementation of a method in a subclass while maintaining a common interface with the superclass. It promotes code reuse, flexibility, and follows the principles of inheritance and polymorphism.

No comments:

Post a Comment