nerdexam
Oracle

1Z0-808 · Question #48

class CD { int r; CD(int r) { this.r=r; } } class DVD extends CD { int c; DVD(int r, int c) { // line n1 } } And given the code fragment: DVD dvd = new DVD(10, 20); Which code fragment should you…

The correct answer is C. super(r); this.c = c. Option C is correct because Java requires an explicit super(r) call as the first statement in DVD's constructor - CD has no no-arg constructor, so the parent constructor must be invoked explicitly with the correct argument. After satisfying the parent, this.c = c simply assigns…

Working with Inheritance

Question

class CD { int r; CD(int r) { this.r=r; } } class DVD extends CD { int c; DVD(int r, int c) { // line n1 } } And given the code fragment: DVD dvd = new DVD(10, 20); Which code fragment should you use at line n1 to instantiate the dvd object successfully?

Options

  • Asuper.r = r; this.c = c;
  • Bsuper(r); this(c);
  • Csuper(r); this.c = c;
  • Dthis.c = r; super(c);

How the community answered

(48 responses)
  • A
    8% (4)
  • B
    4% (2)
  • C
    73% (35)
  • D
    15% (7)

Explanation

Option C is correct because Java requires an explicit super(r) call as the first statement in DVD's constructor - CD has no no-arg constructor, so the parent constructor must be invoked explicitly with the correct argument. After satisfying the parent, this.c = c simply assigns the remaining field on the subclass instance.

  • A fails because super.r = r is a field access, not a constructor call - it never actually invokes CD's constructor, leaving the object improperly initialized and causing a compile error since no implicit super() can be inserted.
  • B fails because this(c) attempts to delegate to another DVD constructor that accepts a single int, which doesn't exist - only DVD(int, int) is defined.
  • D fails because super(c) is not the first statement - this.c = r precedes it, and Java enforces that super() or this() must be the very first line of any constructor body.

Memory tip: Think "parent before self" - whenever a parent class lacks a no-arg constructor, your first job in the child constructor is always super(args), before touching any local fields.

Topics

#constructor chaining#super keyword#inheritance#subclass initialization

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice