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.
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.
URL
is a factory that creates a URLConnection
based (if memory serves me correctly) by a scheme. You can have HttpsURLConnection
or HttpURLConnection
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With