0

I have the following class:

public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

I want to add the following constructor:

public MyGLSurfaceView(Context context, MyRenderer myRenderer) {

I tried:

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();
    }

but it wont let me set the renderer before calling the default constructor of MyGLSurfaceView.

How to set a variable before calling the default constructor?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • You can't, and you shouldn't need to. Reconsider. – user207421 May 31 '20 at 21:15
  • @user207421 I want to create an instance of this class but pass a custom renderer – Guerlando OCs May 31 '20 at 21:16
  • 1
    Does this answer your question? [Initialize field before super constructor runs?](https://stackoverflow.com/questions/15682457/initialize-field-before-super-constructor-runs) – pafau k. May 31 '20 at 21:17
  • We know what you want, and you still can't do it the way you said. However if you have your new constructor call the superclass constructor, then set yor variable, and then call `init()`, it will do what you want. Or else it's impossible. – user207421 May 31 '20 at 21:30

2 Answers2

1

Before you can set any fields, you must finish calling any base constructor (whether that's defined in this class or in the super class). So if you need mRenderer set before init() is called, the best you can do is to separate your two constructors (something like this):

public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;
    static AttributeSet attributeSet = null;

    public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
        super(context, attributeSet);
        this.mRenderer = mRenderer;
        init();
    }

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }
}
Tim Cooke
  • 862
  • 7
  • 14
0

You cant do that since you dont have a object. You can set attribute in a class after you instantiate one of its type.

Arif Akkas
  • 54
  • 6