background image

public class Something {
   public int addOne(final int x) {
       return ++x;
   }
}

 

答案 : 

 

int x 

 

被修饰成 final 

 

,意味着 x 

 

不能在 addOne method 

 

中被修改。

5.下面代码有什么错误

public class Something {
   public static void main(String[] args) {
       Other o = new Other();
       new Something().addOne(o);
   }
   public void addOne(final Other o) {
       o.i++;
   }
}
class Other {
   public int i;
}

 

答案 :  

 

 

正确。在 addOne method 

 

中,参数 o 

 

被修饰成 final 

 

。如果在 addOne method 里我们

 

修改了 o   

的 reference

 

比如 : o = new Other();) 

 

,那么如同上例这题也是错的。但这里修改的是 o 的 

member vairable

 

成员变量 ) 

 

,而 o   

的 reference 

 

并没有改变。

6.下面代码有什么错误
class Something {
    int i;
    public void doSomething() {
        System.out.println("i = " + i);
    }