Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with HttpURLConnection

 
Karthik Vaidiswaran
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 : java.net.URLConnection
required: java.net.HttpURLConnection
huc = url.openConnection();

When I do System.out.pritln(url.openConnection().getClass()), I get something like
classs sun.net.www.protocol.http.HttpURLConnection.

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

Thanks
Karthik
 
ramprasad madathil
Ranch Hand
Posts: 489
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
http://java.sun.com/docs/books/tutorial/java/javaOO/subclasses.html

tx,
ram.
 
Karthik Vaidiswaran
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ram,

Thanks for the reply.


Regards
Karthik
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic