1. import Java. util. random; 2. 3. // The difference between static final and final is described in this example. 4. public class staticandfinaltest {5. 6. private Static random Rand = new random (47); // 47 is used as a random seed to generate a random number. 7. 8. private Final int A = Rand. nextint (20); 9. 10. private Static final int B = Rand. nextint (20); 11. 12. public static void main (string [] ARGs) {13. staticandfinaltest Sf = new staticandfinaltest (); 14. system. out. println ("SF:" + "A =" + SF. a); 15. system. out. println ("SF:" + "B =" + SF. b); 16. system. out. println ("------------------------------"); 17. staticandfinaltest sf1 = new staticandfinaltest (); 18. system. out. println ("sf1:" + "A =" + sf1.a); 19. system. out. println ("sf1:" + "B =" + sf1. B); 20 .} 21. 22 .}
Running result:
- SF: A = 15
- SF: B = 18
- --------------
- sf1: A = 13
- sf1: B = 18
we can see that in the SF and sf1 objects, the value of A is not unique, however, the value of B is not changed by creating an sf1 object. This is because it is static and has been initialized during loading, rather than initialized every time a new object is created.