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() { } }