DEV Community

Cover image for πŸš€ Understanding Method Overriding, Method Hiding, and Overloading in Java πŸš€
Ravi Sarva
Ravi Sarva

Posted on • Updated on

πŸš€ Understanding Method Overriding, Method Hiding, and Overloading in Java πŸš€

In Java, developers often encounter concepts like Method Overriding, Method Hiding, and Method Overloading. These concepts empower polymorphism, enhancing code clarity and flexibility. Let's explore each concept using examples:

Method Overriding:

Method overriding occurs when a subclass provides its specific implementation of a method inherited from its superclass. This enables altering method behavior while maintaining the method name and signature.

class P {
    public void m1() {
        System.out.println("P class m1 method is called");
    }

    class C extends P {
        @Override
        public void m1() {
            System.out.println("C class m1 method is called");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        P p = new P();
        p.m1();

        P.C c = new P().new C();
        c.m1();

        P p1 = new P().new C();
        p1.m1();
    }
}
Enter fullscreen mode Exit fullscreen mode

The output will be :
P class m1 method is called
C class m1 method is called
C class m1 method is called

Method Hiding:

Method hiding, on the other hand, occurs when a subclass defines a static method with the same signature as a static method in its superclass. Unlike method overriding, where the subclass method overrides the superclass method's behavior, in method hiding, the subclass method shadows the superclass method.

Let's consider an example:

class P {
    public static void m1() {
        System.out.println("P class m1 method is called");
    }
    class C extends P {
        public static void m1() {
            System.out.println("C class m1 method is called");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this scenario, C class defines a static method m1() with the same signature as the static method m1() in class P. However, this is not method overriding; it's method hiding. When invoking static methods, Java binds the method call at compile time, unlike dynamic dispatch in method overriding.

The output will be :
P class m1 method is called
P class m1 method is called
P class m1 method is called

Conclusion:

Understanding method overriding, method hiding, and method overloading is essential for writing clean, flexible, and maintainable Java code. Method overriding enables subclass-specific behavior, method hiding allows subclass methods to shadow superclass methods, and method overloading provides flexibility in method invocation with different parameter lists. By mastering these concepts, Java developers can leverage the power of polymorphism and write efficient and expressive code.

Top comments (0)