Creating an object of an abstract class URLConnection or HttpURLConnection in Java

In the tutorial, I saw the following code:

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

How is this possible? The API says that URLConnection (as well as a subclass of HttpURLConnection) is an abstract class. But abstract classes cannot be created. 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"? This is very strange for me, so can someone explain this to me.

+4
source share
4 answers
 openConnection(); 

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

Based on javadoc :

If the URL protocol (for example, HTTP or JAR) has a public specialized subclass of URLConnection that belongs to one of the following packages or one of its subpackages: java.lang, java.io, java.util, java.net, the connection will be associated with this subclass . For example, for HTTP, an HttpURLConnection will be returned , and for a JAR, a JarURLConnection will be returned.

+3
source

First of all, you are not creating an instance of URLConnection , but a URL at:

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

URLConnection is a variable type (which can be abstract or even an interface ), a URL is a specific class that you create.

About the new word openConnection() returns a URLConnection object, so you do not need to create it yourself.

+1
source

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

+1
source

URLConnection is a truly abstract class. It cannot be created.

Therefore, to be useless, however, for each abstract class in the class structure there must be a subclass (possibly several levels removed), which is specific, i.e. which can be created.

URL.openConnection () returns you one of these subclasses. You can check this with the debugger if you want. URLConnection is the type of link that you call "con", not the type of object that this link refers to.

+1
source

Source: https://habr.com/ru/post/1483178/


All Articles