Why doesn't Java allow overriding of static methods?

后端 未结 22 2728
谎友^
谎友^ 2020-11-21 05:49

Why is it not possible to override static methods?

If possible, please use an example.

22条回答
  •  时光说笑
    2020-11-21 06:34

    Now seeing above answers everyone knows that we can't override static methods, but one should not misunderstood about the concept of accessing static methods from subclass.

    We can access static methods of super class with subclass reference if this static method has not been hidden by new static method defined in sub class.

    For Example, see below code:-

    public class StaticMethodsHiding {
        public static void main(String[] args) {
            SubClass.hello();
        }
    }
    
    
    class SuperClass {
        static void hello(){
            System.out.println("SuperClass saying Hello");
        }
    }
    
    
    class SubClass extends SuperClass {
        // static void hello() {
        // System.out.println("SubClass Hello");
        // }
    }
    

    Output:-

    SuperClass saying Hello
    

    See Java oracle docs and search for What You Can Do in a Subclass for details about hiding of static methods in sub class.

    Thanks

提交回复
热议问题