Shadowing of static methods in Java

In this post, we will discuss the shadowing of static methods in Java. Suppose, we have two classes such that one of them is child class and another is parent class.

Now, if a function in base class has the same name as a function defined in the child class and both of these functions are static, then the base class static function shadows the child class static function. You will understand this with the given example program.

In the given example program, we have created two classes with the name BaseClass and ChildClass. We have defined a static function (Note that the function is static in both classes, child and parent) “fun” for child and base class. These functions produce different outputs. Then in the main function, we create a variable “obj” of the type of Base class and create an instance of Child class and assign it to the variable ‘obj’. Now when we invoke the method fun() using this object it implements its base class version. This is termed as shadowing.

Read this to understand inheritance in Java: What Is Inheritance In Java?

Go through the given example program to grasp the concept fully.

class BaseClass{
  static void fun()
  {
    System.out.println("Base");
  }
}

class ChildClass extends BaseClass{
  static void fun()
  {
    System.out.println("Child");
  }
}

class Main{
  public static void main(String args[])
  {
    BaseClass obj = new ChildClass();
    obj.fun();
  }
}
    
  

The above program gives the output as:

Base

An important point to remember is that when you change the functions as non-static, the above example program will give the output as “Child”.

Hope it was helpful. Thank you.

Also read: Call non static method from static method in Java

Leave a Reply