Java 中是否继承了静态方法? [英] Are static methods inherited in Java?

查看:19
本文介绍了Java 中是否继承了静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读程序员指南Java™ SCJP 认证来自 Khalid Mughal.

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

在继承章节中,它解释了

In the Inheritance chapter, it explains that

成员的继承与其声明的关系密切相关可访问性.如果可以通过简单名称访问超类成员在子类中(不使用任何额外的语法,如 super),成员被认为是继承的

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();
    }
}

如何在 B 类中直接使用 display()?更重要的是,B.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?

推荐答案

所有可访问的方法都由子类继承.

All methods that are accessible are inherited by subclasses.

来自 Sun Java 教程:

From the Sun Java Tutorials:

子类继承其父类的所有公共成员和受保护成员,无论子类在哪个包中.如果子类与其父类在同一个包中,则它也继承父类的包私有成员.您可以按原样使用继承的成员、替换它们、隐藏它们或用新成员补充它们

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members

继承的静态(类)方法和继承的非静态(实例)方法的唯一区别在于,当您编写具有相同签名的新静态方法时,旧的静态方法只是隐藏而不是覆盖.

The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.

来自页面,关于覆盖和隐藏的区别.

From the page on the difference between overriding and hiding.

隐藏和覆盖之间的区别具有重要意义.被调用的重写方法的版本是子类中的版本.被调用的隐藏方法的版本取决于它是从超类调用还是从子类调用

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass

这篇关于Java 中是否继承了静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆