【问题标题】:Why is it said that static methods cannot be inherited? [duplicate]为什么说静态方法不能被继承? [复制]
【发布时间】:2015-01-19 05:04:22
【问题描述】:

我能够运行以下代码:

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

class B extends A
{
    public void show()
    {
        display();
    }
}

public class staticMethodInheritance {
    public static void main(String[] args) {
        B b = new B();
        b.display();
    }
}

现在我可以从 B 类的实例访问方法 display() 那么为什么说静态方法不能被继承。如果我在 B 类中声明了一个方法显示,那么据说超类中的方法是隐藏的,而子类中的方法被调用,那么这又不是我们重写方法时所需的行为。

【问题讨论】:

  • 嗯,它不是。但是方法不能被覆盖(然后继承),只能隐藏。

标签: java


【解决方案1】:

inherited static (class) methods and inherited non-static (instance) 方法的唯一区别是,当您编写具有相同签名的新静态方法时,the old static method is just hidden, not overridden.

静态方法被继承,但不能被覆盖,它们可以被重新定义。

【讨论】:

  • 隐藏而不是覆盖是什么意思。我没有看到行为的差异
  • @kapilchhattani 更多阅读 herehere
  • 我知道这些概念,但我想我没有很好地提出我的问题。但无论如何,谢谢你的回答,我会把你的标记为正确的。
猜你喜欢
  • 1970-01-01
  • 2010-10-20
  • 2016-05-29
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 2015-12-15
  • 2021-03-19
相关资源
最近更新 更多