Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scope: Returning an object instantiated inside a method - Is it dangerous?

Tags:

java

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.

like image 958
Zak Avatar asked Feb 01 '12 22:02

Zak


People also ask

Can an object be created inside a method?

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.

Can an object be returned from a method in Java?

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.

What happens when an object is created inside a function?

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.

What is meant by returning an object from a method?

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.


1 Answers

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.

like image 197
Louis Wasserman Avatar answered Oct 05 '22 22:10

Louis Wasserman