安卓在java中调用默认构造函数之前如何设置变量?
我有以下课程:
public class MyGLSurfaceView extends GLSurfaceView {
MyRenderer mRenderer;
public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init();
}
我想添加以下构造函数:
public MyGLSurfaceView(Context context, MyRenderer myRenderer) {
我试过:
public class MyGLSurfaceView extends GLSurfaceView {
MyRenderer mRenderer;
static AttributeSet attributeSet = null;
public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
this.mRenderer = mRenderer;
this(context, attributeSet);
}
public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init();
}
但是它不允许我在调用MyGLSurfaceView
的默认构造函数之前设置渲染器
如何在调用默认构造函数之前设置变量强>
# 1 楼答案
你不能那样做,因为你没有目标。在实例化一个类的类型后,可以在该类中设置属性
# 2 楼答案
在设置任何字段之前,必须完成对任何基本构造函数的调用(无论该构造函数是在此类中定义的还是在超类中定义的)。因此,如果在调用
init()
之前需要设置mRenderer
,那么最好将两个构造函数分开(如下所示):