关于Activity回调中的@override注解

发布于 2025-01-04 22:19:11 字数 318 浏览 0 评论 0原文

似乎在 Activity 中,例如 onCreate() 方法,如果我有 @Override 注释或不是。他们都工作。 (只要我在回调中调用 super.onCreate() ,它就会调用父类的方法。)

有人可以告诉我为什么我们需要有 @Override Activity 中生命周期回调的注释?

我问这个是因为我在没有 @Override 注释的情况下进行了测试,我的应用程序仍然成功运行。

It seems in an Activity, for example, the onCreate() method, it does not make much difference if I have the @Override annotation or not. They both work. (As long as I call super.onCreate() inside the callback , it will call the parent class' method.)

Can someone tell me why we need to have the @Override annotation for life-cycle callbacks in Activity ?

I ask this because I tested without @Override annotation, my app still running successfully.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光沙漏 2025-01-11 22:19:11

这更像是一种良好的开发实践。

如果您错误地想要重写超类(或实现的接口)中不存在的方法,您将收到错误消息。

认为您想要覆盖“onCreate”,但您拼写错误并写成了“onCreatee”。使用该注释,您将收到错误。如果没有它,您最终会花费大量时间试图理解为什么初始化方法无法正常工作。

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". 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.

难理解 2025-01-11 22:19:11

@Override 注释只是用来告诉编译器我们正在重写代码中的方法。这是出于安全目的,让编译器知道我们函数的目的(即覆盖),如果我们万一重载函数,编译器将返回错误。因此,通过这个注释,我们可以轻松检测重载错误。

The @Override annotation is used just to tell the compiler that we are overriding a method in our code. This is used for safety purposes to let the compiler know the aim of our function (i.e. 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.

还如梦归 2025-01-11 22:19:11

有些人已经提到,捕获名称拼写错误的潜在错误非常有用。

我想补充一点
显示哪些方法是特定于您的类的新方法,哪些是从父类(或接口)继承的。听起来可能不多,但我个人认为它非常有用。

因此,您应该始终使用 @Override 并配置您的 IDE,以便在您忘记时标记错误。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文