声明的变量
public final static int[][] highscores = new int[3][5];
public final static String[][] players = new String[][]{
{"player", "player", "player", "player", "player"},
{"player", "player", "player", "player", "player"},
{"player", "player", "player", "player", "player"},
};
对其进行如下操作
public static void addScore(int diff, String player, int score){
for(int i = 0; i < 5; i++){
if(score > highscores[diff - 3][i]){
for(int j = 4; j > i; j--){
highscores[diff - 3][j] = highscores[diff - 3][j - 1];
players[diff - 3][j] = players[diff - 3][j - 1];
}
highscores[diff - 3][i] = score;
players[diff - 3][i] = player;
break;
}
}
}
为什么没报错,按理说final修饰后应该不能修改
public final static int[][] highscores = new int[3][5];
public final static String[][] players = new String[][]{
{"player", "player", "player", "player", "player"},
{"player", "player", "player", "player", "player"},
{"player", "player", "player", "player", "player"},
};
对其进行如下操作
public static void addScore(int diff, String player, int score){
for(int i = 0; i < 5; i++){
if(score > highscores[diff - 3][i]){
for(int j = 4; j > i; j--){
highscores[diff - 3][j] = highscores[diff - 3][j - 1];
players[diff - 3][j] = players[diff - 3][j - 1];
}
highscores[diff - 3][i] = score;
players[diff - 3][i] = player;
break;
}
}
}
为什么没报错,按理说final修饰后应该不能修改
player也是player = new String[2][2]
如果C++里面用const关键字去修饰一个类的成员函数,C++的编译器会检测这个函数是否更改了这个类的状态,也就是对类成员的写入。Java就没有这么神奇的功能了。final修饰一个函数仅仅代表它不能被子类重写而已
public final static String[][] players = new String[][]{
{"player", "player", "player", "player", "player"},
{"player", "player", "player", "player", "player"},
{"player", "player", "player", "player", "player"},
};这的final修饰的是 highscores这个变量 ,它指向的内存地址不能变,但是他内存地址存放的值是可以改变的
int [][] A = new int[3][5] ;
...
highscores = A ; //这样子是错误的,highscores 指向的对象在内存中的地址不能改变
highscores[0][0] = 1 ;//合法 ,赋值
}
final int i=1;
i=8;直接错,final修饰的变量不可以被修改
1.对于基本类型,一旦被FINAL修饰,他就是一个常量。
final int i =8;
//can't do this:
//i=8;
2.对于对象类型,一旦被FINAL修饰,对象的"指针"但不能再指向其它的对象。
class A{int b = 0;}
final a = new A();
//can't do this:
//a = new A();
//but you can do this:
a.b = 3;
也就是说JAVA没有提供常量对象的机制,而在C++中是有这种机制的。