简体   繁体   English

关于Activity回调中的@override注释

[英]About @override annotation in Activity callbacks

It seems in an Activity , for example, the onCreate() method, it does not make much difference if I have the @Override annotation or not. 它似乎在一个Activity中 ,例如onCreate()方法,如果我有@Override注释,它没有太大的区别。 They both work. 他们都工作。 (As long as I call super.onCreate() inside the callback , it will call the parent class' method.) (只要我在回调中调用super.onCreate() ,它就会调用父类的方法。)

Can someone tell me why we need to have the @Override annotation for life-cycle callbacks in Activity ? 有人能告诉我为什么我们需要为Activity中的生命周期回调提供@Override注释吗?

I ask this because I tested without @Override annotation, my app still running successfully. 我问这个因为我测试没有@Override注释,我的应用程序仍然成功运行。

This is more like a good development practice. 这更像是一种良好的开发实践。

If by mistake you want to override a method that doesn't exist in the super class (or interfaces implemented) you'll get an error. 如果您想要覆盖超类(或实现的接口)中不存在的方法,则会出现错误。

Think that you want to override "onCreate" but you misspell it and write "onCreatee". 认为你想要覆盖“onCreate”,但你拼错它并写上“onCreatee”。 With that annotation, you'll get an error. 使用该注释,您将收到错误。 Without it, you'd end up spend a lot time trying to understand why your initialization method was not working properly. 没有它,你最终会花费大量时间来理解为什么你的初始化方法不能正常工作。

The @Override annotation is used just to tell the compiler that we are overriding a method in our code. @Override注释仅用于告诉编译器我们正在覆盖代码中的方法。 This is used for safety purposes to let the compiler know the aim of our function (ie to override) and if we are overloading a function by any chance, the compiler will return an error. 这用于安全目的,让编译器知道我们的函数的目标(即覆盖),如果我们任何机会重载函数,编译器将返回错误。 Hence with this annotation, we can detect overloading mistakes easily. 因此,通过此注释,我们可以轻松地检测到重载错误。

Some already mentioned that it is very useful to catch potential bugs with wrongly spelled names. 有人已经提到,用错误的拼写名称捕获潜在的错误是非常有用的。

I would like to add that it also shows which methods are new methods specific to your class and which are inherited from the parent class (or interface). 我想补充一点,它还显示哪些方法是特定于您的类的新方法,哪些方法是从父类(或接口)继承的。 It might not sound like much, but I personally find it very useful. 听起来可能不是很多,但我个人认为它非常有用。

So you should always use @Override and configure your IDE to flag an error if you forget it. 因此,您应始终使用@Override并配置IDE以在忘记错误时标记错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM