Shadowing of static functions in Java

2.5

In Java, if name of a derived class static function is same as base class static function then the derived class static function shadows (or conceals) the base class static function. For example, the following Java code prints “A.fun()”

// file name: Main.java
class A {
   static void fun() {
      System.out.println("A.fun()");
   }
}

class B extends A { 
   static void fun() {   
      System.out.println("B.fun()");
   }
}

public class Main {
   public static void main(String args[]) {
      A a = new B();
      a.fun();  // prints A.fun()
   }
}

If we make both A.fun() and B.fun() as non-static then the above program would print “B.fun()”.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.5 Average Difficulty : 2.5/5.0
Based on 36 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.