我正在阅读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程序员知道什么时候做这种铸造,什么时候不?