In the Android documentation here: http://developer.android.com/guide/components/fragments.html A Fragment implements an interface.
In the onAttach() callback, it seems to cast the current Activity to an interface. Conceptually, how is this possible and is the same type of cast standard practice in vanilla Java?
public static class FragmentA extends ListFragment {
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
OnArticleSelectedListener mListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
...
}
Some basic knowledge about the topic:
Think about an
interfaceas a bundle of functions. If aclassimplements aninterface, then it guarantees, that it has all the interfaces functions implemented.In your case:
If you have an object and you don’t need more than the functions of an interface, that your object implements, then you can treat (and cast) that object to that interface. This way you loose “information” about your object, because you won’t be able to use its functions (except the interface functions), but sometimes its enough.