java - 为什么实例方法不能重写静态方法

标签 java inheritance

class Abc{
public  static void hello(){
    System.out.println("parent");//Line1
 }
}

class Abc1 extends Abc{
public  void hello(){//Line2
    System.out.println("child");//Line3
 }
}

编译器在第 3 行给出错误,指出

This instance method cannot override the static method from Abc

为什么静态方法不能被实例方法覆盖?

最佳答案

简单:因为语言规范是这么说的。

这是静态方法的缺点之一:它们没有多态性!从概念上讲,它们不应该被覆盖。这就是全部内容。

准确地说:JLS说静态和非静态方法和状态之间的区别:

An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

关于java - 为什么实例方法不能重写静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43848140/

相关文章:

java - 使用保留下划线的 xjb 覆盖 JAXB 属性名称

javascript Riddle : 2 objects that seem identical with respect to constructor, 原型(prototype)和 __proto__ 链接,行为不同

c++ - 所有带有 "recursion"的 child 的静态变量

java - Hibernate 继承 SingleTable

c# - C#中没有继承的装饰器模式。这样对吗?

java - 在 Java 主类中使用带有继承的类

java - Spring事务管理调度器

java - Android 布局的内部类

java - 括号内带有 % 符号的模式匹配

Java Socket 超时异常,什么会导致这些错误