Why Static method cannot be overridden in java - Explanation with program


Why Static method cannot be overridden in java>
It's one of the favourite question of interviewers. Intention is to test few basic core java concepts.
Static method cannot be overridden in java, any attempt to do this will not cause compilation error, but the results won’t be same when we would have overridden non-static methods.
But why?
Overriding in Java means that the method would be called on the run time based on type of the object and not on the compile time type of it .

But static methods are class methods access to them is always resolved during compile time only using the compile time type information.


Accessing static method using object references is a bad practice (we must access static variable using Class Name) and just an extra liberty given by the java designers.

EXAMPLE>
In below program access to SuperClass’s static method() is resolved during compile time  only using the compile time type information (i.e. by using SuperClass obj), means calling obj.method() is always going to invoke static method() of SuperClass.
Assign any sub type object to reference of superclass [obj=new SubClass()] won’t have any impact on call to static method at runtime.

Accessing static method using object references is bad practice (discussed above) and just an extra liberty given by the java designers.

Program to static method cannot be overridden in java>
class SuperClass{
   static void method(){
          System.out.println("superClass method");
   }
}
class SubClass extends SuperClass{
   static void method(){
          System.out.println("SubClass method");
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class StaticMethodTest {
  
   public static void main(String[] args) {
          SuperClass obj=new SubClass();
          obj.method();
   }
         
}
/*OUTPUT
superClass method
*/

If non-static methods would have been used in above program, output would have been
subClass method



Important points you must know about overriding static methods in java >
  • Static method cannot be overridden, any attempt to do this will not cause compilation error. (Discussed above)

  • Static method cannot be overridden with non-static method, any attempt to do this will cause compilation error.

  • Non-static method cannot be overridden with static method, any attempt to do this will cause compilation error.




RELATED LINKS>

Static keyword in java - variable, method, class, block - 20 salient features


Labels: Core Java
eEdit
Must read for you :