Derek Zhu
Derek Zhu

Reputation: 183

java construct method overload with multi match

Refer to the code below:

public class ExpandableTextView extends TextView {

    public ExpandableTextView(Context context) {
        this(context, null, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        this(context, attrs, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs, Runnable runnable) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();
            }
        });
    }

    public ExpandableTextView(Context context, AttributeSet attrs, Activity activity) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();
            }
        });
    }
}

method like this(context, null, null); could refer to two other constructor methods, is there any way that i can specify which one it refers to rather than changing the signature or the "null"? thanks

Upvotes: 0

Views: 85

Answers (2)

Raman Shrivastava
Raman Shrivastava

Reputation: 2953

Your code should not work as Compiler will throw error mentioning ambiguous method. Because Java will always try to use the most specific applicable version of a method that's available (see JLS §15.12.2). And null is a valid value for the types Context, AttributeSet and Runnable. Therefore all 3 version are applicable.

Upvotes: 0

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16152

Sure, just cast the null into the signature type!

    new ExpandableTextView(context, (AttributeSet)null, (Runnable)null)

Upvotes: 2

Related Questions