Skip to main content

Can we override a static method in Java ?

Points To Remember
  • Static methods can not be overriden.
  • Static methods are at class level and not at object level.
  • Static methods take lock on a class and non static methods takes lock on an object.

Example : Trying to override a static method
Suppose we have a class A and another class B that extends this class. Both the classes have same static method test() with same return type and same parameters. So this satisfies this the conditions for overriding a function. So what will be the output of the following program ?

class A{
public static void test(){
System.out.println("Class A");
}
}


public class B extends A{

public static void main(String args[]){
A obj1 = new B();
B obj2 = new B();
obj1.test();
obj2.test();
A.test();
B.test();
}

public static void test(){
System.out.println("Class B");
}

}
Class A
Class B
Class A
Class B
So, why did we get this output ? Incase it was a case of overriding we should have got the output of obj1.test() and obj2.test()  as Class B. So this is definitely not the case of overriding.

We get this because method test() is static and belongs to class and not any object. Thus when we call obj1.test(), we get a reference of class A, thus it will call the test() of class A and when we do obj2.test(), we get a reference of class B, thus it will call the test() of class B.

Now, lets see what happens if we remove the static keyword from the methods,

class A{
public void test(){
System.out.println("Class A");
}
}


public class B extends A{

public static void main(String args[]){
A obj1 = new B();
obj1.test();
}

public void test(){
System.out.println("Class B");
}

}
Class B

So, now the method test() of class A gets overridden, this is why we get Class B as the output.

Comments