In the android tutorials, The GridView tutorial to be exact, there is a line of code
GridView gridview = (GridView) findViewById(R.id.gridview);
Which looks to be declaring/instantiating a GridView object named, gridview and assigning from …
(GridView)
Now is the (GridView) in parens, the expected return type of findViewById or is it telling where to find findViewById since that doesn’t appear to be connected to an object (although, it would appear to be a member function of a GridView object)??
I believe that the findViewById returns an object of type GridView specified by the resource id of gridview (that we specied in main.xml) and probably now exists after we, earlier, called setContentView(R.layout.main);
So, what is being specified with the (GridView) part of the syntax and what is specifically meant by the parenthesis?
findViewByIdreturns aView, which is an abstract base class for all of Android’s UI.GridViewinherits from other views that eventually inherit fromView. SofindViewByIdwill take the ID you pass it and return the associated view as aView. The(GridView)casts theViewto aGridView, allowing you to use the additional functionality of theGridViewclass.You would receive a
ClassCastExceptionif you tried to cast the result to something other than aGridViewor one ofGridView‘s super classes.