Given the definition of the Vehicle class:
class Vehicle {
int distance;
Vehicle(int x) {
this.distance = x;
}
public void increSpeed(int time) {
int timeTravel = time;
class Car { // line n1
int value = 0;
public void speed() {
value = distance / timeTravel; // line n2
System.out.println("Velocity with new speed " + value + " kmph");
}
}
new Car().speed(); // line n3
}
}
and this code fragment:
Vehicle v = new Vehicle(100);
v.increSpeed(60);
What is the result?
A.
Velocity with new speed 1 kmph
B. A compilation error occurs at line n1.
C. A compilation error occurs at line n2.
D. A compilation error occurs at line n3.
题解
Java 8 之后的版本,允许方法内的区域内部类别(local inner class),使用方法内的区域变量而不一定要是常数,但仅能取得变量数值,无法更改变量数值。
在这个题目中,Vehicle 类别和其方法内的区域内部类别 Car,都可以正常的编译。
程序实体化出 Vehicle 对象之后,会透过构造器将 distance 对象字段设为 100。接着使用 Vehicle 对象的 increSpeed 方法,调用其 Car 区域内部类别对象中的 speed 方法,设置 value 变量的值为 distance 字段的值 100,再除上传入 increSpeed 方法的参数值 60。由于变量型态均为整数,因此进行除法运算时,会自动舍弃掉小数点的部份,value 变量的值会被重新指派为 1。程序第 17 行,将 value 的值输出。
