【问题标题】:Why is it impossible to have a static method in the subclass with the same signature as in parent class? [duplicate]为什么在子类中不可能有一个与父类具有相同签名的静态方法? [复制]
【发布时间】:2015-12-16 19:09:55
【问题描述】:

为什么子类中不能有与父类相同签名的静态方法?

class Parent {
    public final static void fun() {
        System.out.println("parent");
    }
}

public class Child extends Parent {        
    // doesn't compile! 
    public static void fun() {
        System.out.println("child");
    }
}

我只是想知道为什么他们在这里允许 final 修饰符?我们都知道静态方法属于一个类,不属于对象,所以不可能在子类中重写该方法。所以我final在这里多余。

【问题讨论】:

  • 您可以在子类中重新定义静态方法。 +1 @Michael 的回答指出编译失败的确切原因。

标签: java


【解决方案1】:

您将该方法声明为final,这意味着您将其密封。 final 方法不能由子类重新定义。根据 Oracle,

在方法声明中使用 final 关键字表示该方法不能被子类覆盖

【讨论】:

  • 这对于实例方法是正确的,但对于类方法不是。
  • @user3552363 阅读重复的问题。对于类方法,final 防止隐藏父类的方法。
猜你喜欢
  • 2011-12-24
  • 1970-01-01
  • 2013-04-18
  • 1970-01-01
  • 2011-09-01
  • 1970-01-01
  • 2013-07-26
  • 2018-01-16
  • 2014-10-04
相关资源
最近更新 更多