我正在閱讀Java Programming Interviews Exposed這本書。他們提供此代碼示例,我不明白:爲什麼我需要在此Java示例中投射HttpURLConnection?
@Test
public void makeBareHttpRequest() throws IOException {
final URL url = new URL("http", "en.wikipedia.org", "/");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
final InputStream responseInputStream = connection.getInputStream();
final int responseCode = connection.getResponseCode();
final String response = IOUtils.toString(responseInputStream);
responseInputStream.close();
assertEquals(200, responseCode);
System.out.printf("Response received: [%s]%n", response);
}
是否有關於當一個變量需要投(右側)一些通用的規則?爲什麼是它HttpURLConnection的澆鑄在右側的位置:
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
但responseInputStream不需要右側這裏定投:
final InputStream responseInputStream = connection.getInputStream();
如何做一個Java程序員知道什麼時候做這種鑄造,什麼時候不?