试图理解这段代码对 HttpURLConnection 意味着什么
Trying to understand what this code means for HttpURLConnection
我正在查找以前由离开公司的同事编写的示例代码。但是我无法理解用 Abstract class 名称定义方法的意义是什么 achieve
这是导入语句
import java.net.HttpURLConnection;
还有一个方法写成
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;
}
现在我在 https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html 上阅读 HttpURLConnection 并注意到它是一个抽象的 class。但是还不明白用 class 名称定义方法的目的是什么。它应该像一种数据类型吗?
private static HttpURLConnection <methodname>
基本上是做什么的?
A class 是数据类型,而不是类似的数据类型。
写一个类似
的方法
DataTypeName methodName(…) { … }
表示 methodName
returns 对类型 DataTypeName
对象的引用。
DataTypeName
是否是其他 class 的超class 与该定义并不真正相关,它是否被声明为 abstract
.
abstract
的使用仅仅意味着摘要class必须被subclassed;您不能实例化抽象对象 class.
在您的示例中,这意味着可以有多个不同的子 class,但是此例程将它们都视为类型 HttpURLConnection
。这就是简单的面向对象的多态性。
我正在查找以前由离开公司的同事编写的示例代码。但是我无法理解用 Abstract class 名称定义方法的意义是什么 achieve
这是导入语句
import java.net.HttpURLConnection;
还有一个方法写成
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;
}
现在我在 https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html 上阅读 HttpURLConnection 并注意到它是一个抽象的 class。但是还不明白用 class 名称定义方法的目的是什么。它应该像一种数据类型吗?
private static HttpURLConnection <methodname>
基本上是做什么的?
A class 是数据类型,而不是类似的数据类型。
写一个类似
的方法 DataTypeName methodName(…) { … }
表示 methodName
returns 对类型 DataTypeName
对象的引用。
DataTypeName
是否是其他 class 的超class 与该定义并不真正相关,它是否被声明为 abstract
.
abstract
的使用仅仅意味着摘要class必须被subclassed;您不能实例化抽象对象 class.
在您的示例中,这意味着可以有多个不同的子 class,但是此例程将它们都视为类型 HttpURLConnection
。这就是简单的面向对象的多态性。