nerdexam
Oracle

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

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?

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)
  • A
    4% (2)
  • B
    2% (1)
  • C
    10% (5)
  • D
    84% (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 - Object would only appear if you had called new Object()
  • B is wrong because sc = asc reassigns sc to point at the AnotherSampleClass instance; the original SampleClass object it referenced is discarded
  • C reverses the output - sc correctly shows AnotherSampleClass but asc was never reassigned and was always an AnotherSampleClass, never a SampleClass

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.

Full 1Z0-809 Practice