Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object of abstract class URLConnection or HttpURLConnection in Java

I saw the following code in a tutorial:

URLConnection connection = new URL("http://example.com").openConnection();

How is that possible? The API says that URLConnection (and also the Subclass HttpURLConnection) is an abstract class. But abstract classes cannot be instantiated. I also saw other tutorials with (for example) this code:

URL url = new URL( "http://java-tutor.com/index.html" );
URLConnection con = url.openConnection();

Why is there no 'new'? For me that's very strange, so can someone explain this to me.

like image 872
Michael Langhammer Avatar asked May 28 '13 14:05

Michael Langhammer


2 Answers

openConnection();

creates an instance of implementation of URLConnection class (sun.net.www.protocol.http.HttpURLConnection @Credit goes to Sotirios).

Based on javadoc:

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

like image 136
kosa Avatar answered Sep 30 '22 07:09

kosa


URL is a factory that creates a URLConnection based (if memory serves me correctly) by a scheme. You can have HttpsURLConnection or HttpURLConnection.

like image 23
Buhake Sindi Avatar answered Sep 30 '22 08:09

Buhake Sindi