2015-09-07 11:44:36 -06:00
|
|
|
// reuse/FinalData.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// The effect of final on fields
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
class Value {
|
|
|
|
int i; // Package access
|
2017-05-01 14:33:10 -06:00
|
|
|
Value(int i) { this.i = i; }
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
public class FinalData {
|
|
|
|
private static Random rand = new Random(47);
|
|
|
|
private String id;
|
|
|
|
public FinalData(String id) { this.id = id; }
|
|
|
|
// Can be compile-time constants:
|
|
|
|
private final int valueOne = 9;
|
|
|
|
private static final int VALUE_TWO = 99;
|
|
|
|
// Typical public constant:
|
|
|
|
public static final int VALUE_THREE = 39;
|
|
|
|
// Cannot be compile-time constants:
|
|
|
|
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 };
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public String toString() {
|
2016-01-25 18:05:55 -08:00
|
|
|
return id + ": " + "i4 = " + i4
|
|
|
|
+ ", INT_5 = " + INT_5;
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
FinalData fd1 = new FinalData("fd1");
|
2015-12-18 11:28:19 -08:00
|
|
|
//- fd1.valueOne++; // Error: can't change value
|
2015-06-15 17:47:35 -07:00
|
|
|
fd1.v2.i++; // Object isn't constant!
|
|
|
|
fd1.v1 = new Value(9); // OK -- not final
|
|
|
|
for(int i = 0; i < fd1.a.length; i++)
|
|
|
|
fd1.a[i]++; // Object isn't constant!
|
2015-12-18 11:28:19 -08:00
|
|
|
//- fd1.v2 = new Value(0); // Error: Can't
|
|
|
|
//- fd1.VAL_3 = new Value(1); // change reference
|
|
|
|
//- fd1.a = new int[3];
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(fd1);
|
|
|
|
System.out.println("Creating new FinalData");
|
2015-06-15 17:47:35 -07:00
|
|
|
FinalData fd2 = new FinalData("fd2");
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(fd1);
|
|
|
|
System.out.println(fd2);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
fd1: i4 = 15, INT_5 = 18
|
|
|
|
Creating new FinalData
|
|
|
|
fd1: i4 = 15, INT_5 = 18
|
|
|
|
fd2: i4 = 13, INT_5 = 18
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|