1Z0-803 · Question #103
Given: 1. public class SampleClass { 2. public static void main (String[] args) { 3. AnotherSampleClass asc = new AnotherSampleClass(); 4. SampleClass sc = new SampleClass(); 5. // insert code here 6.
The correct answer is B. sc = asc;. To compile, a superclass reference must be assigned a subclass object due to the 'is-a' relationship in Java inheritance, allowing upcasting without an explicit cast.
Question
Options
- Aasc = sc;
- Bsc = asc;
- Casc = (Object) sc;
- Dasc = sc.clone;
How the community answered
(29 responses)- A10% (3)
- B79% (23)
- C3% (1)
- D7% (2)
Why each option
To compile, a superclass reference must be assigned a subclass object due to the 'is-a' relationship in Java inheritance, allowing upcasting without an explicit cast.
Assigning a superclass object to a subclass reference is downcasting and requires an explicit cast, which may still fail at runtime if the object is not actually an instance of the subclass.
In Java, a reference variable of a superclass type (`SampleClass`) can point to an object of its subclass (`AnotherSampleClass`); this is known as upcasting and is implicitly allowed because a subclass object 'is-a' superclass object.
Casting a `SampleClass` object to `Object` before assigning it to an `AnotherSampleClass` reference does not resolve the type incompatibility for downcasting.
`.clone` is an incorrect syntax to call the `clone()` method, and even if corrected, the return type would need to be explicitly cast to `AnotherSampleClass`.
Concept tested: Java inheritance and type casting
Source: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Topics
Community Discussion
No community discussion yet for this question.