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.
Santosh says
package test.com;
public class StaticOverride1
{
public static void so1()
{
System.out.println(“SO1”);
}
}
package test.com;
public class StaticOverride2 extends StaticOverride1
{
public static void so1()
{
System.out.println(“SO2”);
}
public static void main(String[] args)
{
StaticOverride2 so=new StaticOverride2();
so.so1();
}
}
Why can’t we override the static methods in the above code i have executed.
javainterviewpoint says
This phenomenon is called as Method Hiding. Parent class methods that are static are not part of a child class even though they are accessible
Suppose, if you are creating object like below
StaticOverride1 so=new StaticOverride2();
so.so1();
This will call the StaticOverride1 method and not the StaticOverride2 method, this because static methods are bonded using static binding at compile time.