我需要调用“super.XXX”吗?每当我重写一个方法时?
比如说,如果我不在超类 Activity
的重写方法中调用 super.onPause
,那么当 onPause()
为叫。但是,当我在类的方法(onCreate
、onStartCommand
、...)中没有 super.XXX
调用时,不会显示错误派生自服务
。
那么什么情况下我应该在重写方法中调用 super.XXX
呢?
Say, if I don't call super.onPause
in a override method from superclass Activity
, I would get an error when onPause()
is called. But errors don't show up when I have no super.XXX
calls in methods (onCreate
, onStartCommand
, ...) of a class derived from Service
.
So on what conditions should I call super.XXX
in a override method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
文档告诉您您需要调用
onPause
如果您派生Activity
类:Service
文档在onStartCommand
文档。一般来说(不是特别在 Android 中),当您派生时,您应该调用超类的方法,除非您知道不应该这样做。这是一个需要根据具体情况做出的决定,但默认情况下(我想说)是你这样做。
The documentation tells you that you need to call
onPause
if you derive theActivity
class:The
Service
docs don't require that in theonStartCommand
documentation.In general (not specifically in Android stuff), when you derive, you should call through to the superclass's methods unless you know you shouldn't. It's a decision that needs to be case-by-case, but the default (I'd say) would be that you do it.
对此不可能给出有用的答案。它完全取决于重写方法和被重写方法的预期目的和行为。
如果您不知道,则需要执行以下一项或多项操作:
在这种特殊情况下, javadoc 给出了明确的答案。
It is not possible to give a useful answer to this. It entirely depends on the intended purpose and behavior of the override method and the method being overridden.
If you don't know, you need to do one or more of the following:
In this particular case, the javadoc gives a clear answer.
如果手册如 @tj-crowder 所说,您必须致电他们。
它说
如果不是,那么原因是,如果您正在调用函数,您是否希望启动“正常”行为?
例如,如果您重写
onKeyDown()
您可以在按下某个键(例如“后退”)后执行某些操作。然后你可以选择:You must call them if the manual says so as @t-j-crowder said.
it says
If not, then the reasoning is that if you are calling a function, do you want the 'normal' behaviour to be started?
For instance, if you override the
onKeyDown()
You could do something after a certain key is pressed (e.g. 'back'). Then you have the choice:客户端代码只能知道子类
Activity
(称之为MyActivity
),客户端代码无法知道Activity
。但是,MyActivity
可以知道它的基类 Activity。如果重写的方法
onPause()
与其基类相同,则无需显式重写它。Client code can only know subclass
Activity
(call itMyActivity
), Client code cannot knowActivity
. However,MyActivity
can know its base class Activity.If the overridden method
onPause()
is same as its base class, you don’t need to override it explicitly.基于Android文档:与Activity生命周期回调方法不同,服务生命周期回调方法不需要调用这些回调方法的超类实现。
Based on Android document: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods for service lifecycle callback methods.