Friday 1 August 2014

Is overriding of static methods possible in Java ?

No, static methods can not be overridden, but they can hide the parent static methods. Because static methods are class level methods, so access to static methods resolved at compile time, where as instance methods are object level, so access to them resolved at run time.

Example
public class SuperClass {
    static void print(){
       System.out.println("In static super class print method");
    }
    
    void show(){
        System.out.println("In super class show method");
    }
}

public class SubClass extends SuperClass{
     static void print(){
       System.out.println("In static sub class print method");
    }
    
     @Override
    void show(){
        System.out.println("In sub class show method");
    }
    
    public static void main(String args[]){
        SuperClass obj = new SubClass();
        
        obj.show();
        obj.print();
    }
}


Output
In sub class show method
In static super class print method

Observe output, 'obj.show' calls subclass show method, where as 'obj.print' calls super class print method.



                                                             Home

No comments:

Post a Comment