nerdexam
Oracle

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…

Working with Inheritance

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

(67 responses)
  • A
    1% (1)
  • B
    6% (4)
  • C
    9% (6)
  • D
    84% (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 returns class Object for a non-Object instance - it always reflects the concrete runtime class.
  • B is wrong because sc was reassigned to reference the AnotherSampleClass object; the original SampleClass instance it created is now unreferenced and irrelevant.
  • C swaps the labels - sc would print AnotherSampleClass (correct), but it incorrectly claims asc prints SampleClass, 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

#polymorphism#object references#getClass() method#inheritance

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice