What is static method shadowing in Java

Static method shadowing in Java:

method shadowing comes up when we have methods with same name and parameter in both super class and sub class. For example, let’s take a look at the below program:

package com.company;

class SuperClass {
    public void printMessage(){
        System.out.println("Inside super class");
    }
}

public class ChildClass extends SuperClass{

    public void printMessage(){
        System.out.println("Inside child class");
    }
    public static void main(String[] args) {
        SuperClass superClass = new ChildClass();

        superClass.printMessage();
    }
}

Here, we have two classes SuperClass and ChildClass. Both classes contains one method each defined with the same name and parameters : printMessage. This method prints one message. This message is different in child and super class.

In the main method, we are creating one object of ChildClass and assigning that value to a variable superClass, which is of type SuperClass. We are calling printMessage method on this object. It prints the below output:

Inside child class

As you can see here, it printed the message in the child class.

Method shadowing of shadowing method:

If we change the above methods to static, it will look as like below:

package com.company;

class SuperClass {
    static public void printMessage(){
        System.out.println("Inside super class");
    }
}

public class ChildClass extends SuperClass{

    static public void printMessage(){
        System.out.println("Inside child class");
    }
    public static void main(String[] args) {
        SuperClass superClass = new ChildClass();

        superClass.printMessage();
    }
}

It will print :

Inside super class

This is because, static methods are not belonged to any instance of class. So, overriding of these methods are not possible. We can either call them using the classname or base class static method shadows the child class static method.

You might also like: