Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以使用super.someMethod在Java中初始化成员变量吗?_Java_Android_Oop - Fatal编程技术网

我可以使用super.someMethod在Java中初始化成员变量吗?

我可以使用super.someMethod在Java中初始化成员变量吗?,java,android,oop,Java,Android,Oop,它只是像这样简单的Android代码 有一个文本视图和一个列表视图 public class MaintActivity extends Activity { private TextView text = (TextView)super.findViewById(R.id.text); //cause android application crash public void onCreate(Bundle savedInstanceState){

它只是像这样简单的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
    }
}

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

一般来说,在Java中初始化变量时调用方法没有错。然而,在这种具体情况下:

private TextView text = (TextView)super.findViewById(R.id.text);
您不能在
onCreate()之前调用
findViewById()
。代码将NPE,因为活动
窗口
尚未设置。另外,您可能希望在
setContentView()
之后调用它,这样它实际上就有机会返回某些内容

一般来说,在Android活动中,在
onCreate()

之前,您不应该在运行时做任何事情,正如laalto所说,真正的问题不是
super
关键字的使用,而是
NullPointerException
由于
活动
onCreate()
中设置之前找不到视图

至于你的题目本身:是的,你可以,你已经自己测试过了

如果您将代码“修复”为:(使用与您相同的代码),则此操作将正常运行


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

错误是什么?顺便说一句,编译错误!=运行时异常!=崩溃。这似乎是一个运行时异常,因为当我注释掉它并在OnCreat成员方法中初始化X时,我去掉了crashion。必须有一个堆栈跟踪,您可以为我们发布吗?如果没有它,我们无法进一步帮助您。很抱歉,现在我使用android代码,请帮帮我。我的坏,现在我使用代码,请帮帮我:)谢谢您的回答,使用这个或根本不使用关键字更好是什么意思?对于大多数功能,您实际上不需要使用
super
。您只需键入
setContentView(R.layout.main)
this.text=(TextView)findViewById(R.id.text)
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);
    }
}