Are static methods inherited in Java?

2018-12-31 09:32发布

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

In the Inheritance chapter, it explains that

Inheritance of members is closely tied to their declared accessibility. If a superclass member is accessible by its simple name in the subclass (without the use of any extra syntax like super), that member is considered inherited

It also mentions that static methods are not inherited. But the code below is perfectlly fine:

class A
{
    public static void display()
    {
        System.out.println("Inside static method of superclass");
    }
}

class B extends A
{
    public void show()
    {
        // This works - accessing display() by its simple name -
        // meaning it is inherited according to the book.
        display();
    }
}

How am I able to directly use display() in class B? Even more, B.display() also works.

Does the book's explanation only apply to instance methods?

14条回答
裙下三千臣
2楼-- · 2018-12-31 09:58

This concept is not that easy as it looks. We can access static members without inheritance, which is HasA-relation. We can access static members by extending the parent class also. That doesn't imply that it is an ISA-relation (Inheritance). Actually static members belong to the class, and static is not an access modifier. As long as the access modifiers permit to access the static members we can use them in other classes. Like if it is public then it will be accessible inside the same package and also outside the package. For private we can't use it anywhere. For default, we can use it only within the package. But for protected we have to extend the super class. So getting the static method to other class does not depend on being Static. It depends on Access modifiers. So, in my opinion, Static members can access if the access modifiers permit. Otherwise, we can use them like we use by Hasa-relation. And has a relation is not inheritance. Again we can not override the static method. If we can use other method but cant override it, then it is HasA-relation. If we can't override them it won't be inheritance.So the writer was 100% correct.

查看更多
查无此人
3楼-- · 2018-12-31 09:59

All the public and protected members can be inherited from any class while the default or package members can also be inherited from the class within the same package as that of the superclass. It does not depend whether it is static or non static member.

But it is also true that static member function do not take part in dynamic binding. If the signature of that static method is same in both parent and child class then concept of Shadowing applies, not polymorphism.

查看更多
登录 后发表回答