Monday 12 November 2012

Quickly implement constructors based on a superclass in Eclipse

package com.bc.android;

import android.view.View;

public class MyCustomView extends View
{
}


How annoying is it when you inherit from another class and you get this error:

Implicit super constructor View() is undefined for default constructor. Must define an explicit constructor

This means we need to implement at least one of the constructors from the superclass in the subclass.

Turns out Eclipse makes it easy to pick and choose what constructors you want to implement and automatically inserts these constructors into your code.

Open the Source menu and select "Generate Constructors from Superclass..."


Now set a check mark on every constructor you want to implement in your subclass and hit OK.


And there you have it! Three constructors automatically implemented that use the correct parameter list and call the constructor of the superclass.

Here's the final result:


package com.bc.android;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

public class MyCustomView extends View
{
    public MyCustomView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public MyCustomView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public MyCustomView(Context context)
    {
        super(context);
        // TODO Auto-generated constructor stub
    }
}

No comments:

Post a Comment