1Z0-808 · Question #74
Given: public class SampleClass { public static void main(String[] args) { AnotherSampleClass asc = new AnotherSampleClass(); SampleClass sc = new SampleClass(); sc = asc; System.out.println("sc: "…
The correct answer is D. sc: class AnotherSampleClass asc: class AnotherSampleClass. getClass() returns the runtime type of the actual object in memory - not the declared type of the reference variable. After sc = asc, both sc and asc point to the same AnotherSampleClass instance, so both print class AnotherSampleClass, making D correct. Why the distractors…
Question
Options
- Asc: class Object asc: class AnotherSampleClass
- Bsc: class SampleClass asc: class AnotherSampleClass
- Csc: class AnotherSampleClass asc: class SampleClass
- Dsc: class AnotherSampleClass asc: class AnotherSampleClass
How the community answered
(67 responses)- A1% (1)
- B6% (4)
- C9% (6)
- D84% (56)
Explanation
getClass() returns the runtime type of the actual object in memory - not the declared type of the reference variable. After sc = asc, both sc and asc point to the same AnotherSampleClass instance, so both print class AnotherSampleClass, making D correct.
Why the distractors fail:
- A is wrong because
getClass()never returnsclass Objectfor a non-Object instance - it always reflects the concrete runtime class. - B is wrong because
scwas reassigned to reference theAnotherSampleClassobject; the originalSampleClassinstance it created is now unreferenced and irrelevant. - C swaps the labels -
scwould printAnotherSampleClass(correct), but it incorrectly claimsascprintsSampleClass, which never happened.
Memory tip: Think of a reference variable as a label on a box - getClass() tells you what's inside the box, not what the label says. Reassigning the label (sc = asc) makes it point to a new box, so getClass() reflects the new box's contents.
Topics
Community Discussion
No community discussion yet for this question.