Saturday 27 September 2014

Overriding of static method in Java.

So in my previous post which is on overriding in java I mentioned that static methods can’t be overridden .Yes, its true that we cannot override static methods .But hold on when I tried the following program it worked :
package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
 Public static void disp(){
  System.out.println("in parent");
 }
}


public class child extends Parent{
 public  static void disp(){
  System.out.println("in child");
 }

 public static void main(String[] args) {
  child c= new child();
  p.disp();
 
 
 }
}
And there is output also as :
In child

Without any compilation error .
Ok, so I will explain you this thing that overriding happens at runtime not at compilation time .Its actually dynamic binding .This thing which is happening in the above example is method hiding means If you declare,  another static method with same signature in derived class than static method of super class will be hidden, and any call to that static method in sub class will go to static method declared in that class itself. This is known as method hiding in Java.


I will explain you this with an example . Suppose we have 2 classes one parent and other child and we have a static method disp() in both classes which is actually overridden in child class then by rule of overriding method of that class should be resolved with the object of class used to call that method but instead of that in case of static method its being resolved by reference . eg. In the example given below if I am using parent reference and object of child then method of parent class will be called instead of parent class because static methods are dealt or resolved at compile time .
package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
 Public static void disp(){
  System.out.println("in parent");
 }
}


public class child extends Parent{
 public  static void disp(){
  System.out.println("in child");
 }

 public static void main(String[] args) {
Parent p= new child();
  p.disp();
 
 
 }
}

Then output will be :
In parent
In the case below with child class reference  
package test;

import java.util.ArrayList;
import java.util.List;

 class Parent
{
 Public static void disp(){
  System.out.println("in parent");
 }
}


public class child extends Parent{
 public  static void disp(){
  System.out.println("in child");
 }

 public static void main(String[] args) {
  child c= new child();
  p.disp();
 
 
 }
}

Output will be :
In child

See also :





No comments:

Post a Comment