1Z0-808 · Question #42
Given: ``java class Vehicle { String type = "4W"; int maxSpeed = 100; Vehicle(String type, int maxSpeed) { this.type = type; this.maxSpeed = maxSpeed; } } class Car extends Vehicle { String trans…
The correct answer is E. Compilation fails only at line n1. Option E is correct because Car(String trans) at line n1 does not explicitly call a super(...) constructor, so Java automatically inserts super() - but Vehicle has no no-arg constructor (defining any explicit constructor removes the default one), causing a compile error. Line…
Question
class Vehicle {
String type = "4W";
int maxSpeed = 100;
Vehicle(String type, int maxSpeed) {
this.type = type;
this.maxSpeed = maxSpeed;
}
}
class Car extends Vehicle {
String trans;
Car(String trans) { //line n1
this.trans = trans;
}
Car(String type, int maxSpeed, String trans) { //line n2
super(type, maxSpeed);
this.trans = trans;
}
}
And given the code fragment:
7. Car c1 = new Car("Auto");
8. Car c2 = new Car("4W", 150, "Manual");
9. System.out.println(c1.type + " " + c1.maxSpeed + " " + c1.trans);
10. System.out.println(c2.type + " " + c2.maxSpeed + " " + c2.trans);
What is the result?Options
- A4W 100 Auto
- B4W 150 Manual
- CNull 0 Auto
- D4W 150 Manual
- ECompilation fails only at line n1
- FCompilation fails at both line n1 and line n2
How the community answered
(61 responses)- A5% (3)
- B2% (1)
- C2% (1)
- D18% (11)
- E64% (39)
- F10% (6)
Explanation
Option E is correct because Car(String trans) at line n1 does not explicitly call a super(...) constructor, so Java automatically inserts super() - but Vehicle has no no-arg constructor (defining any explicit constructor removes the default one), causing a compile error. Line n2 compiles fine because it explicitly calls super(type, maxSpeed), which matches the Vehicle(String, int) constructor exactly. Options A, B, C, and D are all wrong because they assume the code compiles and produces runtime output - it never gets that far. Option F is wrong because only n1 is broken; n2's explicit super(...) call is perfectly valid.
Memory tip: Whenever a parent class declares any constructor, assume the no-arg constructor is gone. If a subclass constructor doesn't start with an explicit super(...), Java silently tries super() - and if that doesn't exist, compilation fails immediately at that constructor.
Topics
Community Discussion
No community discussion yet for this question.