简体   繁体   中英

What will happen If I initialize a Class object which is already initialized in JAVA?

I want to know what will happen if I initialize an already initialized Class object in Java. Does the garbage collector destroys the object and free the memory?.

Example code:

........
Object target = new MyClass();//First intialization
........
target = new MyClass();//Re-intialization //I want to know what will happen here
........
Object target = new MyClass();

This will create a new object of MyClass() and target variable will refer to this object.

After the second statement:

target = new MyClass();

Another new Object will be created and target will now refer to this newly created object. The previous object will have no reference and GC will free that memory.

MyClass 的第一个对象将不再在线程上处于活动状态,垃圾收集器会在堆上需要更多内存时激活并释放空间,这是 Java 虚拟机使用的一大块内存。

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