Which constructors can be inserted at (1) in MySub
without causing a compile-time error?.
class MySuper {/*w ww . j a v a2s . c o m*/ int number; MySuper(int i) { number = i; } } class MySub extends MySuper { int count; MySub(int count, int num) { super(num); this.count = count; } // (1) INSERT CONSTRUCTOR HERE }
Select the one correct answer.
(a) MySub() {} (b) MySub(int count) { this.count = count; } (c) MySub(int count) { super(); this.count = count; } (d) MySub(int count) { this.count = count; super(count); } (e) MySub(int count) { this(count, count); } (f) MySub(int count) { super(count); this(count, 0); }
(e)
The class MySuper
does not have a default constructor.
This means that constructors in subclasses must explicitly call the superclass constructor and provide the required parameters.
The supplied constructor accomplishes this by calling super(num) in its first statement.
Additional constructors can accomplish this either by calling the superclass constructor directly using the super()
call, or by calling another constructor in the same class using the this()
call which, in turn, calls the superclass constructor.
(a) and (b) are not valid, since they do not call the super- class constructor explicitly.
(d) fails, since the super()
call must always be the first statement in the constructor body.
(f) fails, since the super()
and this()
calls cannot be combined.