Whenever we add ‘final’ in front of a variable, it means we can’t change the variable under any circumstances. In this example we use an int variable number, but we write it as NUMBER so we know it’s a constant.
// jamesprogram.java
class jamesprogram {
public static void main (String[] args){
cat catObject = new cat(10);
for (int i=0;i<5;i++){
catObject.add();
System.out.printf("%s", catObject);
}
}
}
//cat.java
public class cat {
private int sum;
// declare final variable
// as soon as we assign something to NUMBER
// (initialize it) it cannot be changed, EVER
// after that point
private final int NUMBER; // Contants are in caps
public cat(int x){
NUMBER=x;
}
public void add(){
sum+=NUMBER;
}
public String toString(){
return String.format("sum = %d\n", sum);
}
}
Outputs:
sum = 10
sum = 20
sum = 30
sum = 40
sum = 50