i'm trying to understand some scenario i ran into related to method-reference. i have a method that create an object and then return a method reference based on that object. when the function ends, and i'm using this method reference outside , the response corresponds to the object that was created inside the method. wasn't it was supposed to be deleted by the garbage collector? how come i can still see it after the method ends?
import java.util.function.Function;
public class A {
public String str;
public A(){}
public A(String str){
this.str = str;
}
public String print(String msg) {
return msg + " " + this.str;
}
public Function<String, String> func(){
A a = new A("cat");
return a::print;
}
public static void main(String[] args) {
A a1 = new A();
Function<String, String> foo = a1.func();
System.out.println(foo.apply("animals: "));
}
}
the output is:
animals: cat
i expected some error, not "cat".