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 的值輸出。