Sunday, September 2, 2012
The answer to this question is NO. You cannot override static methods in Java. In order to show this,have a look at code below :

public class SuperClass{
   public static void show(){
      System.out.println("Static SuperClass Method");
   }
}

public class SubClass extends SuperClass{
    public static void show(){
       System.out.println("Static SubClass Method");
    }
}

public class Demo{
    public static void main(String[] args){
        SuperClass ob1=new SuperClass();
         SuperClass ob2=new SubClass();
        SubClass ob3=new SubClass();
         ob1.show();
         ob2.show();
         ob3.show();
    }    
}
The above code will give output as below :
Static SuperClass Method
 Static SuperClass Method
 Static SubClass Method
 If the static method had been overridden then the second line of the output would have been same as that of third line. So the method has not been overridden and a brand new method has been created in sub class. To understand it more deeply just rewrite the sub class as shown below :
public class SubClass extends SuperClass{
    @Override
    public static void show(){
       System.out.println("Static SubClass Method");
    }
}
If you write the latter one you won't be able to compile it. The compiler will tell that there is no such method in super class. So it is recommended that you always use the @Override annotation to verify that whether you have correctly overridden the method or not. So instead of getting an unexpected output you will get a compile time error which is better and easy for debugging. This is possible only with jdk1.5.0 and above.
REASON : The reason why static methods cannot be overridden is that the concept of inheritance is a concept of object. Now static methods and variables are class specific features and not object specific while non-static things are object specific features and for that reason only you can access static things directly using class name. Though static things can be accessed through objects yet they are related to classes and bound with them. Many of you may confuse with this. That's why C# does not allow you to access any static things with objects and thus have removed this confusing feature of Java.

0 comments:

Post a Comment

Total Pageviews

Followers


Labels

Popular Posts

free counters