【问题标题】:Can I use super.someMethod to init a member variable in Java? [closed]我可以使用 super.someMethod 在 Java 中初始化成员变量吗? [关闭]
【发布时间】:2014-07-15 07:43:03
【问题描述】:

这只是简单的 Android 代码

有一个文本视图和一个列表视图。

public class MaintActivity extends Activity {
    private TextView text = (TextView)super.findViewById(R.id.text);
    //cause android application crash
    public void onCreate(Bundle savedInstanceState){
          super.onCreate(savedInstanceState);
          super.setContentView(R.layout.main);
          //when I write this.text = (TextView) super.findViewById(R.id.text); here, I get rid of crashing
    }
}

【问题讨论】:

  • 错误是什么?顺便说一句,编译错误!= 运行时异常!= 崩溃。
  • 这似乎是一个运行时异常,因为当我将其注释掉并在 OnCreat 成员方法中初始化 X 时,我摆脱了崩溃。
  • 必须有一个堆栈跟踪,您可以为我们发布吗?没有它,我们将无法为您提供进一步的帮助。
  • 对不起,我现在放上android代码,请帮帮我。

标签: java android oop


【解决方案1】:

一般来说,在 Java 中初始化变量时调用方法是没有错的。但是,在这种特定情况下:

private TextView text = (TextView)super.findViewById(R.id.text);

您不能在onCreate() 之前调用findViewById()。该代码将 NPE,因为尚未设置活动 Window。你也可能想在setContentView() 之后调用它,这样它实际上就有机会返回一些东西。

在一般的 Android 活动中,您不应该在运行时在 onCreate() 之前做任何事情。

【讨论】:

    【解决方案2】:

    调用超类方法并从中获取返回值通常没有错。您正在调用的特定方法,或者您调用它的方式,或者您对结果所做的操作可能存在问题,但仅调用超类方法并将其结果分配给变量并不是错误.

    【讨论】:

    • 我的错,现在我放上代码请帮帮我:)
    【解决方案3】:

    作为 laalto 的answered,真正的问题不是使用super 关键字,而是NullPointerException 由于ActivityonCreate() 中设置之前无法找到视图。

    至于你的问题标题本身:是的,你可以,而且你已经自己测试过了。

    如果您将代码“修复”为:(使用与您的代码相同的代码),这将毫无错误地运行

    public class MaintActivity extends Activity {
        private TextView text;
    
        public void onCreate(Bundle savedInstanceState){
              super.onCreate(savedInstanceState);
              super.setContentView(R.layout.main);
              this.text = (TextView) super.findViewById(R.id.text);
        }
    }
    

    不过,在这种情况下很奇怪,因为setContentView()findViewById() 肯定不会被覆盖。最好使用this 或根本不使用关键字。

    【讨论】:

    • 感谢您的回答,您的意思是使用这个关键字或根本不使用关键字更好?
    • 大部分功能都不需要使用super。您只需输入setContentView(R.layout.main);this.text = (TextView) findViewById(R.id.text);
    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    相关资源
    最近更新 更多