File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Problem with HttpURLConnection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with HttpURLConnection" Watch "Problem with HttpURLConnection" New topic

Problem with HttpURLConnection

Karthik Vaidiswaran

Joined: Jan 11, 2005
Posts: 16
I call openConnection() method on a URL object. I try to assign this to HttpURLConnection reference ,

url = URL(...); //LINE 1
HttpURLConnection huc = url.openConnection(); //LINE 2

I am getting an error which says

incompatible types
found :
huc = url.openConnection();

When I do System.out.pritln(url.openConnection().getClass()), I get something like

I expected the class to be of type Please tell me why the class is different. Please help me in fixing the error I get in line 2 of code

ramprasad madathil
Ranch Hand

Joined: Jan 24, 2005
Posts: 489

try this...

con.openConnection() returns an object of type URLConnection. Now URLConnection is an abstract class and what it actually returns is an object of a concrete sub class. sub-class objects can be referenced by super class variable in this fashion.

When u have a variable of type subclass and you require that variable to point to the subclass object (currently pointed to by the superclass variable), you have to specifically cast it like this

for more info

Karthik Vaidiswaran

Joined: Jan 11, 2005
Posts: 16
Hi Ram,

Thanks for the reply.

Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
A better solution (in my opinion) is to change the type of your variable:

One purpose of the superclass-subclass relationship is to provide an abstract interface through the superclass where each subclass provides the details for a specific implementation. Unless you absolutely need methods that are provided only by the subclass, you should use superclass references rather than subclass references.

This is a very fundamental concept in object-oriented design and programming. It would definitely be beneficial for you to study up on inheritence and related topics (such as polymorphism).

Keep Coding!


Java API Documentation
The Java Tutorial
subject: Problem with HttpURLConnection
It's not a secret anymore!