Alcance de Java: devolver un objeto instanciado dentro de un método: ¿es peligroso?

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.

preguntado el 01 de febrero de 12 a las 22:02

Can't say I understand what you're asking here. What do you mean by "jump out of it's original scope"? Are you a C++ programmer? -

You are confusing scope with lifetimes. Think of scope as pertaining to variables, lifetime to objects. -

2 Respuestas

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.

Respondido 02 Feb 12, 02:02

Esto es perfectamente normal.

The garbage collector cannot collect it because the it's still referred to by your a campo.

Unlike C++, Java objects are never linked to the scope that created them.

Respondido 02 Feb 12, 02:02

,"Unlike C++, Java objects are never linked to the scope that created them." -> That's incorrect. If an object is created within a function body and a reference to it is not "leaked out" in the form of a return argument or by some other means, then its lifetime IS linked to the scope in which it was created i.e. once that object is out of scope, it is eligible for garbage collection. You may need to rephrase that last line. - eternan00b

@SiddharthaShankar: Although that is true, the object is not explicitly vinculado to the scope. Rather, it just happens to have the same lifetime. - SLaks

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.