Given:
public class SampleClass {
public static void main(String[] args) {
AnotherSampleClass asc = new AnotherSampleClass();
SampleClass sc = new SampleClass();
sc = asc;
System.out.println("sc: " + sc.getClass());
System.out.println("asc: " + asc.getClass());
}
}
class AnotherSampleClass extends SampleClass {
}
What is the result?
A.
sc: class Object
asc: class AnotherSampleClass
asc: class AnotherSampleClass
B.
sc: class SampleClass
asc: class AnotherSampleClass
asc: class AnotherSampleClass
C.
sc: class AnotherSampleClass
asc: class SampleClass
asc: class SampleClass
D.
sc: class AnotherSampleClass
asc: class AnotherSampleClass
asc: class AnotherSampleClass
題解
程式第5行實體化出來的SampleClass物件,會在第6行執行完後不被任何的變數參考到,會在稍候被垃圾回收(Garbage Collection)。
執行程式第7行時,sc和asc都是同一個AnotherSampleClass物件實體,因此呼叫getClass方法會得到相同的結果。