-3

I'm trying to learn android app development from the official developers site and Udacity. Some variables are declared like this:

ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast)

or:

urlConnection = (HttpURLConnection) url.openConnection()

My question is why the types are also included in parentheses? e.g. (ListView) and (HttpURLConnection). Is it a java thing, or is it specific to android?

tanjibpa
  • 129
  • 10

4 Answers4

2

This is an object cast that changes the type of one object to another. It's not unique to Android; this is a Java language feature. There are rules in Java about when this can work. Usually it's used when you want to change the type of one object to one of more specific type so you can call methods that would not otherwise be available in the original type.

In your first example, you showed a cast to type ListView. Without the case, the return type of the method would be View, but you probably want to do something special with it as a ListView, and you know it's a ListView because that's how you declared it in the XML layout. So you cast it like this.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

Its not related to android its object type casting. There can be 2 casting java scenarios

· Upcasting · Downcasting

When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses, it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it is an upcast. We need not use a cast operator in this case. Int his case when you are finding view in xml file using findViewByid it is returning a view object and you are downcasting it to list view so that you can use .

Sahil Shokeen
  • 336
  • 3
  • 22
0

This is nothing but a Type Casting.

in your 1st case

rootview.findViewById(R.id.listview_forecast) 

will return a view not ListView. So in order to get the reference we need to downcast t ListView.

in your 2nd case (HttpURLConnection) url.openConnection()

will return URLConnection not HttpUrlConnection so it is downcast to HttpURLConnection.

BalaramNayak
  • 1,295
  • 13
  • 16
0

ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast)

In this code, (ListView) typecasts the View which is returned by method findViewById(//) to the type ListView .

Similarly (HttpURLConnection) casts the value returned by url.openConnection to the type HttpURLConnection.

For a simpler example, you can convert a float number into integer.

float a = 10.3;
int b = (int) a; // (int) will convert the 'a' into an integer and it's value will be 10

Type casting is a general concept of programming and Java it's not special to android. You can learn more about type casting here : Casting in Java

Tafveez Mehdi
  • 456
  • 3
  • 12