Android的方法覆盖 [英] Android methods overriding

查看:108
本文介绍了Android的方法覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在子类中重写的方法,我们调用此方法中的超类方法,例如:

When we override a method in a subclass, we call the superclass method within this method, for example:

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    width = w ;
    height = h ;

    Log.d(TAG, "onSizeChanged: width " + width + ", height "+ height);

    super.onSizeChanged(w, h, oldw, oldh);
}

那么,为什么我们需要调用 super.onSizeChanged()

我删除行 super.onSizeChanged(),结果是一样的吧。

I delete the line super.onSizeChanged(), and the result is the same as with it.

或在onCreate方法是相同的,我们称之为 super.onCreate()

Or the same in onCreate method, we call super.onCreate().

推荐答案

有一定的方法做必要的事情,比如活动的onCreate和的onPause方法。如果重写他们不调用父类方法,这些事情不会发生,而且该活动将无法正常工作,因为它应该。在其他情况下(通常,当你实现一个接口),没有你覆盖的实现,只有申报,因此没有必要再调用超级方法。

There are certain methods that do essential things, such as onCreate and onPause methods of activity. If you override them without calling the super method, those things won't happen, and the activity won't function as it should. In other cases (usually when you implement an interface) there is no implementation that you override, only declaration and therefore there is no need to call the super method.

还有一件事,有时你覆盖一个方法,你的目的是要改变原有方法的行为,而不是把它扩大。在这种情况下,你不应该调用thesuper方法。对于一个例子是Swing组件的paint方法。

One more thing, sometimes you override a method and your purpose is to change the behavior of the original method, not to extend it. In those cases you should not call thesuper method. An example for that is the paint method of swing components.

这篇关于Android的方法覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆