I was reading a beginners tutorial on android development which had this line in it’s code:
TextView fortune = (TextView) findViewById(R.id.fortune_text);
I’m fairly new to Java, but I understand the basics of creating variables. So making a new int variable:
int someInt = 4;
Looks a bit different from what is going on above. So I guess we are creating an instance of the TextView object, and then we are calling the findViewById method from the TextView class? But why the (TextView) bit? What are we telling java to do here?
The casting in your example has to do with inheritance. The method
findViewByIdreturns an instance/object of the classView– i.e. it returns a View/widget.TextView, which is the kind of object you want to get access to, is a subclass ofView. The casting bit –(TextView)– is your way to inform the compiler of your intentions, that is that you want access to the extended set of methods provided by aTextViewand not just anyView.It would probably be worth checking http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html for more details.