nerdexam
Oracle

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.

Working with Inheritance

Question

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. } 7. } 8. class AnotherSampleClass extends SampleClass { 9. } Which statement, when inserted into line 5, enables the code to compile?

Options

  • Aasc = sc;
  • Bsc = asc;
  • Casc = (Object) sc;
  • Dasc = sc.clone;

How the community answered

(29 responses)
  • A
    10% (3)
  • B
    79% (23)
  • C
    3% (1)
  • D
    7% (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.

Aasc = sc;

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.

Bsc = asc;Correct

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.

Casc = (Object) sc;

Casting a `SampleClass` object to `Object` before assigning it to an `AnotherSampleClass` reference does not resolve the type incompatibility for downcasting.

Dasc = sc.clone;

`.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

#inheritance#polymorphism#type casting#object assignment

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice