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.
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)- A8% (3)
- B5% (2)
- C13% (5)
- D75% (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.
The `Object` class is the root of the Java class hierarchy, but the object's actual runtime type after assignment is `AnotherSampleClass`, not `Object`.
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.
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
Community Discussion
No community discussion yet for this question.