Tuesday, October 7, 2025
HomeLanguagesJavaShadowing of static functions in Java

Shadowing of static functions in Java

In Java, if the name of a derived class static function is the same as a base class static function then the base class static function shadows (or conceals) the derived class static function. For example, the following Java code prints “A.fun()” 
Note: Static method is a class property, so if a static method is called from a class name or object having a class container then the method of that class is called not the object’s method. 
 

Java




// file name: Main.java
 
// Parent class
class A {
    static void fun() { System.out.println("A.fun()"); }
}
 
// B is inheriting A
// Child class
class B extends A {
    static void fun() { System.out.println("B.fun()"); }
}
 
// Driver Method
public class Main {
    public static void main(String args[])
    {
        A a = new B();
        a.fun(); // prints A.fun();
 
        // B a = new B();
        // a.fun(); // prints B.fun()
 
        // the variable type decides the method
        // being invoked, not the assigned object type
    }
}


Output

A.fun()

Note: If we make both A.fun() and B.fun() as non-static then the above program would print “B.fun()”. While both methods are static types, the variable type decides the method being invoked, not the assigned object type
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

RELATED ARTICLES

Most Popular

Dominic
32340 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6709 POSTS0 COMMENTS
Nicole Veronica
11874 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6832 POSTS0 COMMENTS
Ted Musemwa
7091 POSTS0 COMMENTS
Thapelo Manthata
6781 POSTS0 COMMENTS
Umr Jansen
6785 POSTS0 COMMENTS