I am writing a networking code in java and It looks like following:
//Declaring the reference variable
HttpsURLConnection httpsURLConnection = null;
AuthHttpURLConnection authHttpURLConnection = null;
httpsURLConnection = (HttpsURLConnection) ProxyUrlConnection.openConnection(url);
httpsURLConnection.setSSLSocketFactory(getSocketFactory());
authHttpURLConnection = new AuthHttpURLConnection(httpsURLConnection);
I am not the author of ProxyUrlConnection and AuthHttpURLConnection but here is a description of each:
ProxyURLConnection
public class ProxyURLConnection{
public static synchronized URLConnection openConnection(URL url) throws IOException {
URLConnection urlConnection = null;
urlConnection = url.openConnection();
return urlConnection;
}
... more stuff
}
AuthHttpURLConnection
public class AuthHttpUrlConnection() extends HttpURLConnection{
public AuthHttpURLConnection(HttpURLConnection connection) {
super(connection.getURL());
// sets up the auth headers
}
}
And finally HttpURLConnection and HttpsURLConnection
My specific questions:
How am I able to do this casting? openConnection returns an object of URLConnection, how can I do this downcasting and not get any runtime errors?
(HttpsURLConnection) ProxyUrlConnection.openConnection(url);
How is the following implicit upcasting working?
AuthHttpURLConnection(httpsURLConnection);
I know upcasting is always legal but if I do this then isn't the instance become an object of httpURLConnection instead of httpsURLConnection and once that happen how I am able to call a method setSSLSocketFactory on an object of httpURLConnection since this method is only present in httpsURLConnection?