1.final data
The following example shows the basic rules of final keyword:
import java.util.*;
class Value {
int i;
public Value(int i) {
this.i = i;
}
}
public class FinalData {
private static final Random rand = new Random();
private String id;
public FinalData(String id) {
this.id = id;
}
private final int valueOne = 9;
private static final int VALUE_TWO = 99;
public static final int VALUE_THREE = 39;
private final int i4 = rand.nextInt(20);
static final int INT_5 = rand.nextInt(20);
private Value v1 = new Value(11);
private final Value v2 = new Value(22);
private static final Value VAL_3 = new Value(33);
//Arrays
private final int[] a = {1,2,3,4,5,6};
public String toString() {
return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5;
}
public static void main(String[] args) {
FinalData fd1 = new FinalData("fd1");
//!fd1.valueOne++; //Error! Can't change final value
fd1.v2.i++;//Object isn't constant!
fd1.v1 = new Value(9);
for (int i = 0;i < fd1.a.length;i++)
{
fd1.a[i]++;//Object isn't constant
}
//!fd1.v2 = new Value(2);
//!fd1.VAL_3 = new Value(1);
//!fd1.a = new int[3];
System.out.println(fd1);
System.out.println("Creating new FinalData");
FinalData fd2 = new FinalData("fd2");
System.out.println(fd1);
System.out.println(fd2);
}
}
result:
fd1: i4 = 1, INT_5 = 7
Creating new FinalData
fd1: i4 = 1, INT_5 = 7
fd2: i4 = 14, INT_5 = 7
i4 changed,but INT_5 wasn’t.This shows static final data is initialized once upon loading and not each time a new object is created.
2.Blank final provide much more flexibility in the use final keyword,for example,a final field inside a class can be different for each object,and yet retains its immutable qualities.
3.final arguments
When the argument list is declared as final,you can’t change what the argument reference points to.
4.final methods
In recent versions if Java,you can make a method **final**only if you want to explicitly prevent overriding.