Java 1.1 允許我們將自變數設成final 屬性,方法是在自變數列表中對它們進行適當的宣告。這意味著在一個方法的內部,我們不能改變自變數控制程式碼指向的東西。如下所示:
/** * Created by xfyou on 2016/11/2. * final自變數演示 */ public class FinalArguments { void with(final Gizmo g) { //! g = new Gizmo(); // Illegal -- g is final g.spin(); } void without(Gizmo g) { g = new Gizmo(); // OK -- g not final g.spin(); } // void f(final int i) { i++; } // Can't change // You can only read from a final primitive: int g(final int i) { return i + 1; } public static void main(String[] args) { FinalArguments bf = new FinalArguments(); bf.without(null); bf.with(null); } } class Gizmo { public void spin() { } }