为什么我们不能在子类 B 中声明一个与父类 A 中的静态方法具有相同签名的实例方法?
如果我尝试这样做,它会引发编译时错误。
我的问题是,既然父类的静态方法仅限于父类,为什么子类的实例方法不能编译。
让我们通过代码看看:
`
public class A{
static void testStatic(){}
}
public class B extends A{
void testStatic (){}
}
public class Test{
public static void main (String[] args){
A a = new B()
a.testStatic();
}
`
在上面的代码中,由于 A 没有该名称的实例方法,并且由于 Java 允许对象访问静态方法,因此指向“B”的类型“A”的对象 a 可以调用中存在的静态方法它(A 类)。但是编译器抛出错误“实例方法无法重写静态方法”,为什么?
注意:我可以理解一个类是否不允许两个方法使用相同的方法名称,即使一个是实例,另一个是静态的。但我不明白为什么它不允许子类拥有同名的实例。特别是考虑到静态方法不能被重写这一事实。然而,Java允许子类与父类静态方法同名,这称为信息隐藏,但不是覆盖。
最佳答案
编译器会抛出错误,因为这些是语言的规则。来自 Java Language Specification §8.4.8.2 :
If a class C declares or inherits a
static
methodm
, thenm
is said to hide any methodm'
, where the signature ofm
is a subsignature (§8.4.2) of the signature ofm'
, in the superclasses and superinterfaces of C that would otherwise be accessible to code in C.It is a compile-time error if a static method hides an instance method.
(原文强调)。语言很密集(就像 JLS 中的大多数地方一样),但它符合您所描述的情况。 JLS 没有提供我在初读时可以找到的这条规则的基本原理。但稍微思考一下人们如何尝试使这条规则变得不必要,就会明白它为什么存在。
关于java - java中的静态方法和实例方法-父类和子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34524756/