What is the life of a Java Object that is passed a method argument?
For example I have an object Test
class Test{
public string testType(){
.....
}
}
and I have two classes A and B
class classA{
classB b = new classB();
void nextQuestion{
b.start(new Test());
}
}
class classB{
void start(Test test){
doSomething(test.testType());
}
}
so now what is the life of the Test object? Is it only till the end of the start method or will it be alive till the end of classB or while it alive till the end of classA or is something else.
It will stay atleast till the end of start()
method, because it has been declared there, and that is its scope. Beyond that, its existence is in the hands of the garbage collector.
EDIT:
By end of start()
I mean, till that method ends it's execution. And even if you make the changes that you have shown, that Object
is still needed by the start()
method, so it will still only exist atleast till the execution of start()
method is over, beyond that it depends on the garbage collector.
Its life begins when new Test()
is called, and it may be released by the garbage collector any time after the start
method finishes, because it is provable at compile time that it will never be used after that point.
If the start
method were to (for example) set a static field to refer to the object, the garbage collector could not collect it until that reference was released:
private static Test lastTested;
...
void start(Test test){
lastTested = test;
doSomething(test.testType());
}
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