Reputation: 11388
I have two constructors for an expandable list as shown below, and i have one interface shown below as well. now i want to use the same expandlist adapter for two different activities that's why i created two constructors. but the problem is when initialise the constructors, as you see in the 1st constructor when i initilaise the interface object to the 2nd parameter in the constructor, i receive "Redundant casting" while in the 2nd constructor it is mandatory to initialise the interface object to the 2nd parameter which the activity that should implement that interface
please explain why the casting in the 1st constructor is rundant while its manadory in the 2nd one?
update
both activities extends AppCompatActivity
*code:
public MyExpandableList(Context ctx, ActMain actMain, ArrayList<Group> groupList) {
this.mCtx = ctx;
this.mGroupList = groupList;
this.mBTUtils = new BTUtils(ctx);
this.mDevDetailsObserver = (IDeviceDetailsPasser) actMain;//redundant casting, which is not necessary
}
public MyExpandableList(Context ctx, ActConnect actConnect, ArrayList<Group> groupList) {
this.mCtx = ctx;
this.mGroupList = groupList;
this.mBTUtils = new BTUtils(ctx);
this.mDevDetailsObserver = (IDeviceDetailsPasser) actConnect;//manadory casting
}
//interface
public interface IDeviceDetailsPasser {
public void onDevicedetailsChosen(Header header, Details details, int groupPos);
}
Upvotes: 2
Views: 2293
Reputation: 3062
I think in this case, your actMain
implements IDeviceDetailsPasser
, so casting is redundant, while your actConnect
does not implement IDeviceDetailsPasser
, so casting is mandatory.
EDIT:
to handle ClassCastException, use try/catch
try {
mDevDetailsObserver = (IDeviceDetailsPasser) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement IDeviceDetailsPasser");
}
Upvotes: 1
Reputation: 6978
seems like ActMain
already implements IDeviceDetailsPasser
, that's why redundant casting.
Upvotes: 2