I was looking up sample codes that were previously written by colleague who left the firm. But am not able to understand what does defining a method with an Abstract class name achieve
This is the import statement
import java.net.HttpURLConnection;
And there is a method written as
private static HttpURLConnection pullData(url, redirects) throws IOException
try
{
String method = "GET";
HttpURLConnection connection = null;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setInstanceFollowRedirects(false);
int statusCode = connection.getResponseCode();
if (statusCode == 301) {
if (redirects == 0) {
throw new IOException("Stop!");
}
connection.disconnect();
return pullData(url, redirects - 1);
}
catch (IOException ioerror) {
if (connection != null) {
connection.disconnect();
}
throw ioerror;
}
return connection;
}
Now i was reading up on HttpURLConnection on https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html and noticed it is an abstract class. But have not understood what does defining a method with that class name achieves. Is it supposed to be like a data type?
Basically what does private static HttpURLConnection <methodname>
do?
A class is a data type, not like a data type.
Writing a method like
DataTypeName methodName(…) { … }
says that methodName
returns a reference to an object of type DataTypeName
.
It's not really relevant to that definition whether DataTypeName
is a superclass of some other class, nor whether it is declared abstract
.
The use of abstract
simply means that the abstract class must be subclassed; you cannot instantiate an object of an abstract class.
In your example, all it means is that there could several different subclasses, but this routine treats them all like they are of type HttpURLConnection
. That's simple object-oriented polymorphism.