-1

How can i solve this:

Error:(76, 9) error: reference to MyCalendarItem is ambiguous both constructor MyCalendarItem(Context,MyCalendar) in MyCalendarItem and constructor MyCalendarItem(Context,AttributeSet) in MyCalendarItem match

public MyCalendarItem(Context context) {
        this(context, null); //Error showing in this line
    }

    public MyCalendarItem(Context context, MyCalendar myCalendar) {
        this(context);
        this.myCalendar = myCalendar;
    }

    public MyCalendarItem(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyCalendarItem(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
...
...
...
}
Monzur
  • 1,341
  • 14
  • 11

3 Answers3

1

If the first parameter is context and second parameter is null, then there are two constructors for that signature which leads to ambiguity.

Since null parameter do not have any type, the compiler gets confused which method to call in that situation, so the code does not compile.

You can pass null by casting it to either Context or MyCalendar so that the compiler knows which constructor you are trying to use.

Use:

this(context, (AttributeSet) null );

Or:

this(context, (MyCalendar) null ); //this will cause infinite recursion in your case.
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
1

Java doesn't know which constructor it should use. You have to cast null into the type you want.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25
1

The null literal doesn't have a type, so the compiler doesn't know if you meant to call MyCalendarItem(Context, MyCalendar) or MyCalendarItem(Context, AttributeSet). You can resolve this ambiguity by explicitly casting it, e.g.:

public MyCalendarItem(Context context) {
    this(context, (AttributeSet) null);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350