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…
Question
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)- A8% (4)
- B4% (2)
- C73% (35)
- D15% (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 = ris a field access, not a constructor call - it never actually invokesCD's constructor, leaving the object improperly initialized and causing a compile error since no implicitsuper()can be inserted. - B fails because
this(c)attempts to delegate to anotherDVDconstructor that accepts a singleint, which doesn't exist - onlyDVD(int, int)is defined. - D fails because
super(c)is not the first statement -this.c = rprecedes it, and Java enforces thatsuper()orthis()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
Community Discussion
No community discussion yet for this question.