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.
// file name: Main.java // Parent class class A { static void fun() { System.out.println("A.fun()"); } } // B is inheriting A // Base 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 } } |
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.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Shadowing in Java
- Static and non static blank final variables in Java
- Difference between static and non-static method in Java
- Difference between static and non-static variables in Java
- Understanding storage of static methods and static variables in Java
- Why non-static variable cannot be referenced from a static method in Java
- Understanding "static" in "public static void main" in Java
- Are static local variables allowed in Java?
- Assigning values to static final variables in Java
- Comparison of static keyword in C++ and Java
- Static blocks in Java
- Static class in Java
- Static vs Dynamic Binding in Java
- Static methods vs Instance methods in Java
- static keyword in java
- Final static variable in Java
- Static import in Java
- Static Control Flow in Java
- Static Block and main() method in Java
- Understanding public static void main(String[] args) in Java

