Friday, July 22, 2016

Static methods are redefined not overidden...

What will be out put of the following program?
--------------------------------------------------------------
class StaticSuper {
 public static void m1() {
  System.out.println("Super m1");
 }
 public void m2() {
  System.out.println("Super m2");
 }
 public void m3() {
  m1();
  m2();
 }
}
class StaticSub extends StaticSuper {
 public static void m1() {
  System.out.println("Sub m1");
 }
 public void m2() {
  System.out.println("Sub m2");
 }
}
public class Test {
 public static void main(String args[]) {
  StaticSuper ss = new StaticSub();
  ss.m3();
 }
}
--------------------------------------------------------------
Output of the following program will be :
Super m1
Sub m2

The output of the above program proves that Static methods are not overridden they are redefined.
If you try to override the static method then it will be treated as a non overridden method of the sub class. Static methods will be called based on the type of the reference not the object created.


No comments:

Post a Comment