我可以使用super.someMethod在Java中初始化成员变量吗?
它只是像这样简单的Android代码 有一个文本视图和一个列表视图我可以使用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){
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);
}
}