1Z0-809 · Question #90
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. D is correct because getClass() returns the runtime type of the actual object, not the declared type of the reference variable. After sc = asc, both sc and asc point to the same AnotherSampleClass object created by new AnotherSampleClass(), so both print class…
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
(49 responses)- A4% (2)
- B2% (1)
- C10% (5)
- D84% (41)
Explanation
D is correct because getClass() returns the runtime type of the actual object, not the declared type of the reference variable. After sc = asc, both sc and asc point to the same AnotherSampleClass object created by new AnotherSampleClass(), so both print class AnotherSampleClass.
Why the distractors fail:
- A is wrong because neither reference points to a plain
Object-Objectwould only appear if you had callednew Object() - B is wrong because
sc = ascreassignsscto point at theAnotherSampleClassinstance; the originalSampleClassobject it referenced is discarded - C reverses the output -
sccorrectly showsAnotherSampleClassbutascwas never reassigned and was always anAnotherSampleClass, never aSampleClass
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 sc = asc just moves the sc label onto asc's box, so both labels now point to the same AnotherSampleClass box.
Community Discussion
No community discussion yet for this question.