Java SE 8 Programmer II — Question 2
Given the definition of the Vehicle class:
Class Vehhicle {
int distance; //line n1
Vehicle (int x) {
this distance = x;
}
public void increSpeed(int time) { //line n2
int timeTravel = time; //line n3
class Car {
int value = 0;
public void speed () {
value = distance /timeTravel;
System.out.println ("Velocity with new speed"+value+"kmph");
}
}
new Car().speed();
}
}
and this code fragment:
Vehicle v = new Vehicle (100);
v.increSpeed(60);
What is the result?
Velocity with new speed -
Answer options
- A. line n1.
- B. A compilation error occurs at line n2.
- C. A compilation error occurs at line n3.
- D. A compilation error occurs at
Correct answer: A
Explanation
The code will produce 'line n1.' as output because the class Car is defined inside the method increSpeed, and it can access the distance variable. However, there are no compilation errors at lines n2 or n3, making options B and C incorrect. Option D is incomplete and also incorrect.