Where does java reference variable stored?

前端 未结 6 663
醉话见心
醉话见心 2020-12-06 02:29

How does Java\'s reference variable stored? Is that work similar to C pointer?

what I mean by reference variable is myDog in this code

Dog myDog = ne         


        
6条回答
  •  攒了一身酷
    2020-12-06 02:45

    Java works the same way. Be aware that no variable in Java has an object as a value; all object variables (and field) are references to objects. The objects themselves are maintained somewhere (usually on the heap) by the Java virtual machine. Java has automatic garbage collection, so (unlike in C) you don't need to worry about freeing the object. Once all live references to it are out of scope, it will eventually be swept up by the garbage collector.

    For instance:

    Dog myDog = new Dog();
    someMethod(myDog);
    

    passes to someMethod a reference to the dog object that is referenced by myDog. Changes to the object that might occur inside someMethod will be seen in myDog after the method returns.

提交回复
热议问题