nerdexam
Oracle

1Z0-808 · Question #87

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…

The correct answer is B. sc = asc. Option B works because AnotherSampleClass is a subclass of SampleClass, meaning every AnotherSampleClass object is a SampleClass. Assigning a child-type reference (asc) to a parent-type variable (sc) is called upcasting (widening), which Java performs implicitly and safely…

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

(38 responses)
  • A
    5% (2)
  • B
    89% (34)
  • C
    3% (1)
  • D
    3% (1)

Explanation

Option B works because AnotherSampleClass is a subclass of SampleClass, meaning every AnotherSampleClass object is a SampleClass. Assigning a child-type reference (asc) to a parent-type variable (sc) is called upcasting (widening), which Java performs implicitly and safely without any cast syntax.

Why the others fail:

  • A (asc = sc) attempts a downcast without an explicit cast operator. The compiler can't guarantee that the SampleClass reference actually points to an AnotherSampleClass object, so it refuses to compile.
  • C (asc = (Object) sc) casts sc up to Object, making the type even more general. Assigning an Object to an AnotherSampleClass variable is an even wider downcast and won't compile without an explicit (AnotherSampleClass) cast.
  • D (asc = sc.clone) is syntactically invalid - clone is a method and must be called with parentheses (clone()). Even then, clone() returns Object, which still couldn't be assigned to asc without casting.

Memory tip: Think of it as a job posting - a parent class is the job title and a child class is a specific employee. You can always say "this employee fills the role" (child → parent), but you can't say "this job title is specifically this one employee" (parent → child) without a verified check (explicit cast).

Topics

#Inheritance#Type compatibility#Reference assignment#Upcasting

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice