JasperMoneyshot
JasperMoneyshot

Reputation: 357

What happens if you assign a new class on an existing instance?

Just a pretty simple question, in Java if I had an instance of my class set as a global variable, for example:

MyClass mc = new MyClass();

If I then assigned a new instance of the class to it later in the code:

mc = new MyClass();

What happens to the old instance of the class, would it cause a memory leak and is this bad practice?

Cheers.

Upvotes: 2

Views: 533

Answers (2)

This is the entire point of managed memory. You don't need to manually clear or delete an object when you're done with it unless it's holding some other external resource like a network connection. The JVM (or, in this case, Android runtime) keeps track of objects, notices when they're no longer being used by anyone, and reclaims the memory.

Upvotes: 2

tim
tim

Reputation: 467

The first MyClass is removed by garbage collection and mc is assigned to be a new MyClass, unless the first instance of MyClass is being referenced by another variable, in which case garbage collection does not destroy it.

Upvotes: 5

Related Questions