Inheritance of Static Methods in Java
The documentation on inheritance in Java explains that members are inherited based on their accessibility. However, there seems to be a discrepancy when it comes to static methods.
According to the documentation, static methods are not inherited. But the following code demonstrates that static methods can be accessed in subclasses:
How is this possible?
The answer lies in the underlying implementation of inheritance in Java. All methods that are accessible are inherited by subclasses, regardless of their type (static or instance). However, there is a subtle difference between the inheritance of static and instance methods.
When a new static method with the same signature is defined in a subclass, the old static method is hidden rather than overridden. This means that the new static method takes precedence when called from the subclass. However, the original static method can still be accessed using the superclass name.
In contrast, when an instance method is overridden in a subclass, the new instance method completely replaces the old instance method. This is why inherited instance methods cannot be accessed by their simple name in subclasses.
Therefore, although static methods are not explicitly mentioned as inherited in the Java documentation, they are implicitly inherited along with all other accessible members. The only difference in the inheritance of static methods is that they can be hidden by static methods with the same signature in subclasses.
The above is the detailed content of Do Static Methods Inherit in Java?. For more information, please follow other related articles on the PHP Chinese website!