I was reading a beginners tutorial on android development which had this l开发者_StackOverflow中文版ine 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 findViewById
returns an instance/object of the class View
- i.e. it returns a View/widget. TextView
, which is the kind of object you want to get access to, is a subclass of View
. 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 a TextView
and not just any View
.
It would probably be worth checking http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html for more details.
findViewbyId()
returns a View
class. TextView
is a subclass of View
, and it's casting it to TextView
with the (TextView)
part.
So I guess we are creating an instance of the TextView object, and then we are calling the findViewById method from the TextView class?
The TextView fortune
part does not create anything, just declares a variable of type TextView
.
The findViewById()
method returns a View
instance, which is the parent class of all widgets. In order to use it as a TextView
, you have to cast it first.
Basically, the left part of the statement is what you're assigning - the right part (after =) is the source of the value / object:
TextView fortune = (TextView) findViewById(R.id.fortune_text);
The above line declares an object variable of the TextView type, and assigns it to the return of the method findViewById(String)
. The (TextView)
part ensures that the method return is cast to a TextView object. To copy the object, you could write:
TextView someFortune = fortune;
Which is much closer to the syntax of your next line (as you're assigning the same / compatible types).
The next line:
int someInt = 4;
Declares an int
, and just assigns its value (without a method call). Because "4" is an int
, there's no need to explicitly cast its type (it's primitive anyway).
Update:
Explanation of object type casting:
http://www.javabeginner.com/learn-java/java-object-typecasting
Look at the answer by geek_ji posted here "Why do you at all need a typecast" for a very basic understanding.
精彩评论