Java 中的覆盖与阴影
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17153539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Override vs Shadowing in Java
提问by duckduck
What is the difference between overriding and shadowing in particular to this statement “A static method cannot be overriden in a subclass, only shadowed"
覆盖和阴影之间有什么区别,特别是“静态方法不能在子类中被覆盖,只能被隐藏”
回答by Tom G
If you were truly overriding a method, you could call super()
at some point in it to invoke the superclass implementation. But since static
methods belong to a class, not an instance, you can only "shadow" them by providing a method with the same signature. Static members of any kind cannot be inherited, since they must be accessed via the class.
如果您真的要覆盖一个方法,您可以super()
在其中的某个时刻调用以调用超类实现。但是由于static
方法属于一个类,而不是一个实例,您只能通过提供具有相同签名的方法来“隐藏”它们。任何类型的静态成员都不能被继承,因为它们必须通过类访问。
回答by Jalpan Randeri
Overrideing... This term refer to polymorphic behavior for e.g
覆盖... 这个术语指的是多态行为,例如
class A {
method(){...} // method in A
}
class B extends A {
@Override
method(){...} // method in B with diff impl.
}
When you try to invoke the method from class B you get overriden behvaior ..e.g
当您尝试从 B 类调用方法时,您会得到覆盖行为 ..eg
A myA = new B();
myB.method(); // this will print the content of from overriden method as its polymorphic behavior
but suppose you have declared the method with static modifier than by trying the same code
但是假设您已经使用静态修饰符声明了该方法而不是尝试相同的代码
A myA = new B();
myA.method(); // this will print the content of the method from the class A
this is beacuse static methods cant be overriden ... the method in class B just shadow the method from class A...
这是因为不能覆盖静态方法...... B 类中的方法只是隐藏 A 类中的方法......