简体   繁体   中英

Why casting the object is redundant

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);

}

似乎ActMain已经实现了IDeviceDetailsPasser ,这就是为什么冗余的转换。

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");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM