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