Why doesn't Java allow overriding of static methods?

后端 未结 22 2725
谎友^
谎友^ 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:25

    Yes. Practically Java allows overriding static method, and No theoretically if you Override a static method in Java then it will compile and run smoothly but it will lose Polymorphism which is the basic property of Java. You will Read Everywhere that it is not possible to try yourself compiling and running. you will get your answer. e.g. If you Have Class Animal and a static method eat() and you Override that static method in its Subclass lets called it Dog. Then when wherever you Assign a Dog object to an Animal Reference and call eat() according to Java Dog's eat() should have been called but in static Overriding Animals' eat() will Be Called.

    class Animal {
        public static void eat() {
            System.out.println("Animal Eating");
        }
    }
    
    class Dog extends Animal{
        public static void eat() {
            System.out.println("Dog Eating");
        }
    }
    
    class Test {
        public static void main(String args[]) {
           Animal obj= new Dog();//Dog object in animal
           obj.eat(); //should call dog's eat but it didn't
        }
    }
    
    
    Output Animal Eating
    

    According to Polymorphism Principle of Java, the Output Should be Dog Eating.
    But the result was different because to support Polymorphism Java uses Late Binding that means methods are called only at the run-time but not in the case of static methods. In static methods compiler calls methods at the compile time rather than the run-time, so we get methods according to the reference and not according to the object a reference a containing that's why You can say Practically it supports static overring but theoretically, it doesn't.

提交回复
热议问题