Can We Override Static Method in Java?

No, we cannot override static method in Java. We can declare static methods with same signature in subclass but it is not considered overriding as there would not be any run-time polymorphism.

Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in superclass (or base class).

The implementation to be executed is decided at run-time and decision is made according to the object used for call. Note that signatures of both methods must be same. We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence we cannot override a static method in Java. If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class.

Let's take a look at following code example.

// Superclass 
class Base { 
 
    // Static method in base class which will be hidden in subclass  
    public static void display() { 
        System.out.println("Static or class method from Base"); 
    } 
 
     // Non-static method which will be overridden in derived class  
     public void print()  { 
         System.out.println("Non-static or Instance method from Base"); 
    } 
} 
 
// Subclass 
class Derived extends Base { 
 
    // This method hides display() in Base  
    public static void display() { 
         System.out.println("Static or class method from Derived"); 
    } 
 
    // This method overrides print() in Base  
    public void print() { 
         System.out.println("Non-static or Instance method from Derived"); 
   } 
} 
 
// Driver class 
public class Test { 
    public static void main(String args[ ])  { 
       Base obj1 = new Derived(); 
 
       // As per overriding rules this should call to class Derive's static  
       // overridden method. Since static method can not be overridden, it  
       // calls Base's display()  
       obj1.display();   
 
       // Here overriding works and Derive's print() is called  
       obj1.print();      
    } 
} 
 
Output:
Static or class method from Base
Non-static or Instance method from Derived

Hope you have enjoyed reading this post. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.