Why (right side) cast a variable in Java

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com

Interesting:

The question:

Is there some general rule about when a variable needs to be cast (on the right side)? Why is it that HttpURLConnection is cast on the right side here:

final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

but responseInputStream does not need to be cast on the right side here:

final InputStream responseInputStream = connection.getInputStream();

How does a Java programmer know when to do this kind of casting, and when not to?

The answer:

In this program, you cast into HttpURLConnection because you need to use a method that is available in HttpURLConnection, and not available in its parent classes, the method setRequestMethod().

You can do this because you know that your URL is an HTTP URL, and therefore the URLConnection object that will be returned from it is going to be an HttpURLConnection.

You do not cast the result of connection.getInputStream() because it returns InputStream and you don’t need any methods that are not defined in InputStream.

In general, you use the class that gives you the operations that you need – if you know that the result that you are getting is allowed to be cast to that class.

Source