考虑以下示例代码:
1. public class GC {
2. private Object o;
3. private void doSomethingElse(Object obj) { o = obj; }
4. public void doSomething() {
5. Object o = new Object();
6. doSomethingElse(o);
7. o = new Object();
8. doSomethingElse(null);
9. o = null;
10. }
11. }
Run Code Online (Sandbox Code Playgroud)
当调用doSomething方法时,在第5行中创建的Object可用于垃圾收集之后是哪一行?
A.第5行
B.第6行
C.第7行
D.第8行
E.第9行
F.第10行
答案:D
为什么D?确实,当第6行被执行时,第5行中创建的对象现在被实例var o和本地var o引用,当第8行被执行时,对象现在只被本地引用引用,所以为什么要回答是D和第9行执行后会发生什么?谢谢.
i3 = null;在下面显示的类中执行时,有四个对象符合垃圾回收的条件.我添加了评论来解释我是如何得到这个答案的.我的推理是否正确?
public class Icelandic extends Horse{
public void makeNoise(){
System.out.println("vinny");
}
public static void main(String args[]){
/**
* 2 objects created
*/
Icelandic i1 = new Icelandic();
/**
* 2 objects created
*/
Icelandic i2 = new Icelandic();
/**
* 2 objects created
*/
Icelandic i3 = new Icelandic();
/**
* i3 is now pointing at i1, original Icelandic() referred to by i3 now
* has no reference - 2 objects now have no reference
*/
i3 …Run Code Online (Sandbox Code Playgroud)