Are static methods inherited in Java?

后端 未结 14 1668
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:07

    You can experience the difference in following code, which is slightly modification over your code.

    class A {
        public static void display() {
            System.out.println("Inside static method of superclass");
        }
    }
    
    class B extends A {
        public void show() {
            display();
        }
    
        public static void display() {
            System.out.println("Inside static method of this class");
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            B b = new B();
            // prints: Inside static method of this class
            b.display();
    
            A a = new B();
            // prints: Inside static method of superclass
            a.display();
        }
    }
    

    This is due to static methods are class methods.

    A.display() and B.display() will call method of their respective classes.

提交回复
热议问题