@override 注释 [英] @override annotation
问题描述
谁能告诉我这个代码:
public class OvTester {
@Override
public int hashCode() {
return toString().hashCode();
}
}
确定 OvTester
类中的 toString
方法覆盖其超类中的 toString
方法.
determines that the toString
method in the OvTester
class overrides the toString
method in its superclass.
我想知道这是否属实,如果是,它是如何运作的?
I'd like to know if this is true, and if so how it works?
如果这不是真的,那么这是真的:
If it's not true, then is this true:
OvTester
中的hashCode()
方法必须覆盖其超类中的同名方法"
"the hashCode()
method in OvTester
must override the same name method in its superclass"
?
如果这不正确,那么什么是正确的?
If that's not correct then what is correct?
推荐答案
当您在子类中重新定义具有相同签名的方法时,会发生方法覆盖.
Method overriding happens when you redefine a method with the same signature in a sublcass.
所以这里你覆盖了 hashCode()
,而不是 toString()
So here you are overriding hashCode()
, not toString()
@Override
注释是可选的(但这是一件非常好的事情),并表明它应该被覆盖.如果您拼错了某些内容或输入了错误类型的参数,编译器会警告您.
The @Override
annotation is optional (but a very good thing) and indicates that this is expected to be overriding. If you misspell something or have a wrongly-typed parameter, the compiler will warn you.
所以是的,第二个语句是正确的(在这种情况下,超类是 java.lang.Object
)
So yes, the 2nd statement is true (and the superclass in this case is java.lang.Object
)
这篇关于@override 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!