Note that there are some explanatory texts on larger screens.

plurals
  1. POBasic constructor chaining calls
    primarykey
    data
    text
    <p>I hope this is not a silly question.<br> Having 3 basic constructors</p> <pre><code>public MyClass(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public MyClass(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public MyClass(Context context) { super(context); // TODO Auto-generated constructor stub } </code></pre> <p>Each calls the <code>super</code> class constructor first. So does it mean all common constructor code I have to put in a private method like this?:</p> <pre><code>public MyClass(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); common(context); } public MyClass(Context context, AttributeSet attrs) { super(context, attrs); common(context); } public MyClass(Context context) { super(context); common(context); } private void common(Context context) { ... } </code></pre> <p>I though that I could chain the constructor for common code, but I get an error saying constructor calls must be the first statement in the code.</p> <pre><code>public MyClass(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this(context, attrs); } public MyClass(Context context, AttributeSet attrs) { super(context, attrs); // Some code this(context); } public MyClass(Context context) { super(context); // Some more code } </code></pre> <p>And the first statement is either the super constructor call or the class constructor call, cannot be both.</p> <pre><code>Constructor call must be the first statement in a constructor </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload