为什么我们不能覆盖非静态方法以使其成为静态。尝试执行此操作时出现此错误:
此静态方法无法从 SuperClass 中隐藏实例方法。
非常感谢!
覆盖意味着在子类中为实例方法提供新的实现,实例方法可能会也可能不会与类实例成员一起使用。覆盖它们并将它们重新定义为static
. static
表示该方法与类相关,而不是与类的实例相关。
你不能在 C# 和 Java 中做到这一点。
对于 C# 查看覆盖 - MSDN
您不能使用 new、static 或 virtual 修饰符来修改覆盖方法。
Static methods are not overridden in the way Polymorphism works. However when you try to override a static method Java allows the concept of Name Hiding.
Now coming to your question. A Static method can be invoked both by Class Name and Object name. If you override a non static method with a static one how will the compiler know which one to invoke.
static void f(){}
A obj = new A();
A.f()
and obj.f()
will both invoke the static method. If you put a Non-Static f()
here the confusion starts for obj.f()
.