I’m a student in Java class and learned something about Java today that made my gears turn. When I asked the teacher how and why, he wasn’t sure about the behavior. Can anyone explain why the following example works?
class Example {
public int ex_val;
public Example (int a) {
this.ex_val = a;
}
public int getExVal () {
return this.ex_val;
}
}
If I were to create an instance of “Example” inside a method of another class and “return” the object, it can successfully make the jump out of it’s original scope and be used subsequently.
class ParentObject {
// Instance Variables
public Example a;
public ParentObject (int number) {
// Initialize instance variable object from out-of-scope instantiation
this.a = genExample(number);
// Verify scope creep
System.out.println(this.a.getExVal());
}
public Example genExample (int a) {
return new Example(a);
}
}
This DOES work, but is this behavior stable? Can I count on this? Can the garbage collector jump in between the return statement of one method and assignment statement of the calling function? Am I running the risk of failure based on my OS’s version of the JVM? This seems like handy functionality if it can be relied upon.
This is a totally normal, common, and reliable thing to do in Java, and the thing to do is trust that the garbage collector will clean up the object as soon as there aren’t any live references to it. This is not OS-dependent or JVM-dependent: any JVM will be fine with this.