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.
In Java, we can create Objects in various ways: Using a new keyword. Using the newInstance () method of the Class class. Using the newInstance() method of the Constructor class.
In java, a method can return any type of data, including objects. For example, in the following program, the incrByTen( ) method returns an object in which the value of an (an integer variable) is ten greater than it is in the invoking object.
When you declare a variable inside a block of code, then that variable has a lifetime that lasts until the end of the block of code. The variable will be destroyed when its lifetime ends, which is when control exits that block.
It would mean make a copy and return it. The difference is that if you return pointer to objects internal variable that object state could be modified from outside. If you return copy that copy can be modified and the original object will not change.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With