Can we Override static methods in Java

No, We cannot Override a static method in Java. Unlike Overloading of static method we cannot do overriding. When we declare a method with same signature and static in both Parent and Child class then it is not considered as Method Overriding as there will not be any Run-time Polymorphism happening.

When the Child class also has defined the same static method like Parent class, then the method in the Child class hides the method in the Parent class. In the below code we can see that we are having a static display() method in both Parent and Child class.

package com.javainterviewpoint;

import java.io.IOException;

class Parent 
{
    public static void display()
    {
        System.out.println("Welcome to Parent Class");
    }
}
public class Child extends Parent
{
    public static void display()
    {
        System.out.println("Welcome to Child class");
    }
    public static void main(String args[]) 
    {
        //Assign Child class object to Parent reference
        Parent pc = new Child();
        pc.display();
     }
}

Output :

Welcome to Parent Class

As per overriding in Java, the display() method of the Child class should be called, since it is a static method overriding will not happen here and hence the Parent class display() method is called here.

Leave a Reply

Your email address will not be published. Required fields are marked *