Is it possible to override static Method


No, You can not override the static method because as per the nature of static method it belongs to specific class, but you can redeclare/hide it in to the subclass and the subclass doesn't know anything about the parent class static methods, because static specific to only that class in which it has been declared.

First will try to ovveride non-static method and observe the output
Example 1:
  
class SuperClass{
 public void someMethod(){
  System.out.println("Super Class Method");
 }
 
}

public class ChildClass extends SuperClass{
 
 public void someMethod(){
  System.out.println("Child Class Method");
 }

 
 public static void main(String[] args) {
  ChildClass childClass = new ChildClass();
  childClass.someMethod();
  SuperClass superClass = childClass;
  superClass.someMethod();
 }

}
output:
Child Class Method
Child Class Method

next will change the non-static methods to static and observe the output

Example 2:
class SuperClass{
 
 public static void someMethod(){
  System.out.println("Super Class Method");
 }
 
}

public class ChildClass extends SuperClass{
 
 public static void someMethod(){
  System.out.println("Child Class Method");
 }

 
 public static void main(String[] args) {
  ChildClass childClass = new ChildClass();
  childClass.someMethod();
  SuperClass superClass = childClass;
  superClass.someMethod();
 }

}
output:
Child Class Method
Super Class Method


Examples1- we successfully override the super class non-static method and the output of super class is equal to overrided child class method.
Example2 - the child class re-declare/hide the super class static method and super class static method hiden from child class static method.The output will be different from example1 since the super class static method is not overrided by child class.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...