Guest User

Untitled

a guest
Jan 22nd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. package com.garytrakhman.common;
  2.  
  3. public class FinalTest {
  4. private String test;
  5.  
  6. {
  7. // works
  8. new Runnable() {
  9. @Override
  10. public void run() {
  11. System.out.print(test);
  12. }
  13. }.run();
  14. }
  15.  
  16. // Works
  17. void test2() {
  18. new Runnable() {
  19. @Override
  20. public void run() {
  21. System.out.print(test);
  22. // works, test lives within heap in the
  23. // object, so it's not copied, but
  24. // rather referenced
  25. }
  26. }.run();
  27. }
  28.  
  29. void test3() {
  30. final String test2 = null;
  31.  
  32. // 1
  33. new Runnable() {
  34.  
  35. @Override
  36. public void run() {
  37. System.out.print(test2);
  38. // test2 must be final, since it lives on test3()'s stack (the
  39. // ref not the value)... and
  40. // must be allocated to the heap
  41. }
  42. }.run();
  43.  
  44. String test3 = null;
  45. // 2
  46. class TestClass implements Runnable {
  47. private final String test;
  48.  
  49. public TestClass(String test) {
  50. this.test = test;
  51. }
  52.  
  53. @Override
  54. public void run() {
  55. System.out.print(test);
  56. }
  57. }
  58. Runnable a = new TestClass(test3);
  59. // 1 and 2 are equivalent... the reference test3 lives on the function
  60. // stack, a new reference is created in heap due to the TestClass
  61. // constructor
  62.  
  63. test3 = "go";
  64.  
  65. a.run(); // the string within a will be null still
  66.  
  67. // so basically, it's final since it has a double-meaning, changing it
  68. // wouldn't change its meaning within the anonymous inner class object,
  69. // since it's defined on the stack, but must also live on the object's
  70. // heap, get it?
  71. }
  72.  
  73. }
Add Comment
Please, Sign In to add comment