Created
September 9, 2011 00:30
-
-
Save gtrak/1205191 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.garytrakhman.common; | |
public class FinalTest { | |
private String test; | |
{ | |
// works | |
new Runnable() { | |
@Override | |
public void run() { | |
System.out.print(test); | |
} | |
}.run(); | |
} | |
// Works | |
void test2() { | |
new Runnable() { | |
@Override | |
public void run() { | |
System.out.print(test); | |
// works, test lives within heap in the | |
// object, so it's not copied, but | |
// rather referenced | |
} | |
}.run(); | |
} | |
void test3() { | |
final String test2 = null; | |
// 1 | |
new Runnable() { | |
@Override | |
public void run() { | |
System.out.print(test2); | |
// test2 must be final, since it lives on test3()'s stack (the | |
// ref not the value)... and | |
// must be allocated to the heap | |
} | |
}.run(); | |
String test3 = null; | |
// 2 | |
class TestClass implements Runnable { | |
private final String test; | |
public TestClass(String test) { | |
this.test = test; | |
} | |
@Override | |
public void run() { | |
System.out.print(test); | |
} | |
} | |
Runnable a = new TestClass(test3); | |
// 1 and 2 are equivalent... the reference test3 lives on the function | |
// stack, a new reference is created in heap due to the TestClass | |
// constructor | |
test3 = "go"; | |
a.run(); // the string within a will be null still | |
// so basically, it's final since it has a double-meaning, changing it | |
// wouldn't change its meaning within the anonymous inner class object, | |
// since it's defined on the stack, but must also live on the object's | |
// heap, get it? | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment