简体   繁体   中英

What happens when initializing multiple objects in a for loop with the same variable name?

In this loop there is one variable named pawn , but the loop creates 8 Pawn (s) using that one variable. How is this possible? And, are we able to differentiate each pawn that is created from this one variable?

public void setUpChessPieces() {
    for (int i = 0; i < ChessGame.EIGHT; i++) {
        //param 1:row, param 2:col, param 3:player#, param4:chess piece color
        Pawn pawn1 = new Pawn(1, i, 1, "white");
        //squares has a setPiece method
        squares[1][i].setPiece(pawn1);
    }
}

When you say

squares[1][i].setPiece(pawn1);

you save the reference that you created with new . Each time you call new you create a temporary reference named pawn1 , but then you save it with the aforementioned call to setPiece . As long as squares has the reference, it isn't eligible for garbage collection.

A short cook-down of what happens would look like this:

new Pawn(1, i, 1, "white");

The JVM allocates a new Object on the heap.

Pawn pawn1 = new Pawn(1, i, 1, "white");

A reference to the newly allocated Object gets assigned to pawn1 . Think of a reference as a value saying "look for the Object at this place in the Heap".

squares[1][i].setPiece(pawn1);

setPiece is being called with the reference to the Object.

The loop terminates, pawn1 "disappears". This does only mean that pawn1 itself isn't accessible anymore. The Object itself is being stored on the heap and thus won't disappear. This process repeats all over until the loop completes.

The process by which an Object gets destroyed is called garbage-collection and doesn't affect any objects that are still in use (like the Object to which a reference was stored in pawn1 ).

How can these pawns be differentiated?
Thanks to the reference. Each Object is being stored in a different location on the heap. All one has to do is to compare the locations to notice the difference (from a JVM-internal POV).

How is this possible?

It is possible because at each iteration of the for loop a pawn instance is created. pawn1 is just an identifier to the created object . Each object created within the for loop iteration is an independent object stored in heap memory.

Pawn pawn1 = new Pawn(1, i, 1, "white");

And are we able to differentiate each pawn that is created from this one variable?

we can differentiate them by their underlying data, not by the pawn1 identifier. Example would be if each of the pawn objects had overridden the toString() method and you were to print this out you would notice they're different objects unless two different objects have the same underlying data then they would have the same string representation.

A variable is just a pointer to an object (or null , pointing to nothing). If you had a physical chess board and pointed at each pawn with your finger, you could point at 16 distinct objects with the same pointer. It's the same in Java.

You can retrieve each object later by maintaining separate pointers. Your code does that by copying the value of the pawn1 pointer into each of the squares elements.

When the loop ends, the pawn1 pointer (variable) goes out of scope and vanishes, but the squares references remain in scope.

However, if you replace a value from squares without copying somewhere the reference (pointer) to the prior object, you will lose the last reference to that prior object forever and it will become unreachable.

Objects are not "created from [a] variable". They are created from an invocation of new (usually), and a pointer to the resulting object is returned, presumably for assignment to a variable or to participate in some operation. You could also throw away the resulting reference, but that's likely an error.

You can create an object and assign its reference to the same variable that used to hold a different value, just like you can assign different values to any non-final variable, primitive or reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM