java - 静态方法重写

标签 java oop inheritance polymorphism static-methods

class XYZ{
    public static void show(){
        System.out.println("inside XYZ");
    }
}

public class StaticTest extends XYZ {
    public static void  show() {
        System.out.println("inside statictest");

    }

    public static void main(String args[]){
        StaticTest st =new StaticTest();
        StaticTest.show();

    }

}

尽管我们知道静态方法不能被重写。那么到底发生了什么?

最佳答案

静态方法属于类。它们不能被覆盖。但是,如果在子类中定义了与父类静态方法具有相同签名的方法,则会隐藏父类方法。 StaticTest.show() 隐藏了 XYZ.show() 方法,因此 StaticTest.show() 是在代码中的 main 方法。

关于java - 静态方法重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6013574/

相关文章:

ruby-on-rails - rails : too many methods in model

c# - 在实例化时启动大量属性是一种好做法吗?

java - 继承与多态——理解

c++ - 对象继承虚函数运行失败报错

Java 服务层方法 - 主键或 Hibernate 实体参数?如果使用 Spring Boot,哪个更惯用?

java - IvyDE+WTP : How to workaround that ivy library is ignored by WTP?

php - 网站关键词、无限加载、OOP

java - 为什么我允许 "direct access"到对象的 protected 字段,该对象的类是在不同的包中定义的?

java - 在 JPanel 上绘制矩形

java - 永久删除 JAVA_TOOL_OPTIONS 环境变量