当前位置: 首页 > 面试题库 >

如何强制派生类调用超级方法?(就像Android一样)

解翰采
2023-03-14
问题内容

我想知道,当创建新Activity类然后覆盖该onCreate()方法时,在eclipse中我总是会自动添加:super.onCreate()。这是怎么发生的?在抽象类或父类中是否有Java关键字会强制这样做?

我不知道不调用父类是否违法,但是我记得在某些方法中,我没有这样做就引发了异常。这也是Java内置的吗?您可以使用某些关键字来做到这一点吗?或如何完成?


问题答案:

这是Activity#onCreate()-几乎所有评论的来源(原始-
参见〜800行
):

/**
 * Called when the activity is starting.  This is where most initialization
 * should go: calling {@link #setContentView(int)} to inflate the
 * activity's UI, using {@link #findViewById} to programmatically interact
 * with widgets in the UI, calling
 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
 * cursors for data being displayed, etc.
 *
 * <p>You can call {@link #finish} from within this function, in
 * which case onDestroy() will be immediately called without any of the rest
 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
 * {@link #onPause}, etc) executing.
 *
 * <p><em>Derived classes must call through to the super class's
 * implementation of this method.  If they do not, an exception will be
 * thrown.</em></p>
 *
 * @param savedInstanceState If the activity is being re-initialized after
 *     previously being shut down then this Bundle contains the data it most
 *     recently supplied in {@link #onSaveInstanceState}.  <b><i>Note: Otherwise it is null.</i></b>
 *
 * @see #onStart
 * @see #onSaveInstanceState
 * @see #onRestoreInstanceState
 * @see #onPostCreate
 */
protected void onCreate(Bundle savedInstanceState) {
    mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
    mCalled = true;
}

因此,我的猜测是ADT Eclipse插件会自动super.onCreate()为您添加该调用。不过,这完全是猜测。



 类似资料:
  • 问题内容: 存在问题 如果我有一个像这样的类层次结构: 在实例类型为B的情况下,是否可以从main方法调用A的toString? 当然,像o.super.toString()这样的东西不会编译… 问题答案: 您不能这样做,而且是非常故意的:它会破坏封装。 假设您有一个类,该类使用一种方法通过一些业务规则来验证输入,然后调用超类方法。如果调用方可以忽略该覆盖,那么它将使该类变得毫无意义。 如果发现自

  • 问题内容: 因此,此代码的输出为。现在,我想到了一个问题:作为 派生 类对象的 po 怎么能调用作为基类的 PrivateOverride 的私有方法? 问题答案: 因为您在类中定义了main方法。如果将main方法放在Derived类中,它将无法编译,因为在该类中不可见。 class中的po.f()调用不是多态的,因为in 类为,所以in class中的值不会被覆盖。

  • 问题内容: 下面的代码在运行时显然会打印出“ B1 / A2 / B2”。现在,是否可以改为打印“ A1 / A2 / B2”(即A#method2()应该在A而不是B上调用method1())? 注意:我不需要获得传递多态性,这个问题仅出于好奇。 问题答案: 是的,您可以做到。在包 a中 定义A : 在包 b中 定义B : 将测试放入软件包 a中 并运行它。结果是A1 / A2 / B2。当然这

  • 问题内容: 我正在使用具有3级类继承的代码。从最低级别的派生类开始,调用方法2向上层级的语法是什么,例如super.super调用?“中间”类未实现我需要调用的方法。 问题答案: 好吧,这是一种实现方式: 也许不是您想要的东西,但这是最好的python,除非我弄错了。您要问的内容听起来是反Python的,您必须解释为什么要这么做,以便我们为您提供快乐的python做事方式。 另一个示例,也许是您想

  • 代码:- 在这里,当我用mydog对象调用eat()方法时,它会打印出“dog eating”,有没有办法用mydog对象调用base Animal类的eat()方法,比如有没有像这样的东西 我不想使用super(),因为这样它也会从child类调用eat(),所以它会同时打印语句“animal eating”和“dog eating”,这是我不想要的,我想一次只调用一个语句。

  • 给定一个具有一些虚函数的基类,有人能想出一种方法来强制派生类在编译时重写一组虚函数中的一个吗?或者是实现相同目标的类层次结构的另一种提法? 代码中: 我不确定我真的有一个实际的用例,但是当我实现一些松散地遵循这个模式的东西时,我想到了这个问题,并且认为这是一个有趣的问题,需要思考。