1. Overview
1.概述
In this quick tutorial, we’ll have a look at how to use the @Override annotation.
在这个快速教程中,我们将看看如何使用@Override注解。
2. @Override Annotation
2.@Override 注释
In a subclass, we can override or overload instance methods. Overriding indicates that the subclass is replacing inherited behavior. Overloading is when a subclass is adding new behavior.
在子类中,我们可以覆盖或重载实例方法。覆盖表示子类正在替换继承的行为。重载是指子类增加新的行为。
Sometimes, we’ll overload by accident when we actually intended to override. It’s easy to make this mistake in Java:
有时,我们会意外地重载,而实际上我们的目的是重载。在Java中很容易犯这种错误。
public class Machine {
public boolean equals(Machine obj) {
return true;
}
@Test
public void whenTwoDifferentMachines_thenReturnTrue() {
Object first = new Machine();
Object second = new Machine();
assertTrue(first.equals(second));
}
}
Surprisingly, the test above fails. This is because this equals method is overloading Object#equals, not overriding it.
令人惊讶的是,上面的测试失败了。这是因为这个equals 方法是重载了Object#equals,而不是覆盖了它。
We can use the @Override annotation on inherited methods to protect us from this mistake.
我们可以在继承的方法上使用@Override注解来保护我们不犯这种错误。
In this example, we can add the @Override annotation above the equals method:
在这个例子中,我们可以在@Override方法上方添加equals注解。
@Override
public boolean equals(Machine obj) {
return true;
}
At this point, the compiler will raise an error, informing us that we aren’t overriding equals like we think.
在这一点上,编译器会引发一个错误,告知我们并没有像我们想象的那样覆盖equals。
Then, we can correct our mistake:
然后,我们可以纠正我们的错误。
@Override
public boolean equals(Object obj) {
return true;
}
Because of how easy it’s to accidentally overload, it’s a common recommendation to use the @Override annotation on all inherited methods.
由于不小心重载很容易,通常建议在所有继承的方法上使用@Override注解。
3. Conclusion
3.总结
In this guide, we saw how the @Override annotation works in Java.
在本指南中,我们看到了@Override注解在Java中的作用。
The full source code for the examples can be found over on GitHub.
这些例子的完整源代码可以在GitHub上找到,。