nerdexam
Oracle

1Z0-803 · 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. This code demonstrates polymorphism in Java where a superclass reference variable can point to a subclass object. The getClass() method then correctly returns the actual runtime type of the referenced object.

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
  • Bsc: class SampleClass
  • Csc: class AnotherSampleClass
  • Dsc: class AnotherSampleClass

How the community answered

(40 responses)
  • A
    8% (3)
  • B
    5% (2)
  • C
    13% (5)
  • D
    75% (30)

Why each option

This code demonstrates polymorphism in Java where a superclass reference variable can point to a subclass object. The `getClass()` method then correctly returns the actual runtime type of the referenced object.

Asc: class Object

The `Object` class is the root of the Java class hierarchy, but the object's actual runtime type after assignment is `AnotherSampleClass`, not `Object`.

Bsc: class SampleClass

While `sc` is declared as `SampleClass`, it is assigned an instance of `AnotherSampleClass`; `getClass()` returns the runtime type of the object, not the declared type of the reference variable.

Csc: class AnotherSampleClass
Dsc: class AnotherSampleClassCorrect

The `sc` reference, initially pointing to a `SampleClass` object, is reassigned to point to the `AnotherSampleClass` object created earlier by `asc`. Therefore, `sc.getClass()` returns the runtime type of the object it currently references, which is `AnotherSampleClass`.

Concept tested: Java polymorphism, object runtime type, getClass()

Source: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html

Topics

#polymorphism#inheritance#object references#getClass()

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice