Are static methods inherited in Java?

后端 未结 14 1394
佛祖请我去吃肉
佛祖请我去吃肉 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 06:01

    Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked.

    Example:

    public class Writer {
        public static void write() {
            System.out.println("Writing");
        }
    }
    
    public class Author extends Writer {
        public static void write() {
            System.out.println("Writing book");
        }
    }
    
    public class Programmer extends Writer {
    
        public static void write() {
            System.out.println("Writing code");
        }
    
        public static void main(String[] args) {
            Writer w = new Programmer();
            w.write();
    
            Writer secondWriter = new Author();
            secondWriter.write();
    
            Writer thirdWriter = null;
            thirdWriter.write();
    
            Author firstAuthor = new Author();
            firstAuthor.write();
        }
    }
    

    You'll get the following:

    Writing
    Writing
    Writing
    Writing book
    

提交回复
热议问题