How can ViewParent be cast into View?

Viewed 426

This code:

(View) contentView.getParent();

I don't quite get it: ViewParent is an interface, View is a class that doesn't implement that interface.

How do they transform into one another?

1 Answers

This works in most cases because most ViewParents are ViewGroups.

ViewGroup extends View and implements ViewParent, so it satisfies both.

The reason that ViewParent is a separate interface is that this won't always work: if you keep going up the tree, you'll eventually find a ViewParent that is not a ViewGroup (specifically, you'll get to the ViewRootImpl), and thus also not a View, and that will result in a ClassCastException.

Related