Are static methods inherited in Java?

后端 未结 14 1387
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 05:08

I was reading A Programmer’s Guide to Java™ SCJP Certification by Khalid Mughal.

In the Inheritance chapter, it explains that

Inherit

14条回答
  •  醉酒成梦
    2020-11-22 05:49

    You can override static methods, but if you try to use polymorphism, then they work according to class scope(Contrary to what we normally expect).

    public class A {
    
        public static void display(){
            System.out.println("in static method of A");
        }
    }
    
    public class B extends A {
    
        void show(){
            display();
        }
    
         public static void display(){
            System.out.println("in static method of B");
        }
    
    }
    public class Test {
    
        public static void main(String[] args){
            B obj =new B();
            obj.show();
    
            A a_obj=new B();
            a_obj.display();
    
    
        }
    
    
    }
    

    IN first case, o/p is the "in static method of B" # successful override In 2nd case, o/p is "in static method of A" # Static method - will not consider polymorphism

提交回复
热议问题