English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Sorry for the spaghetti code, but the formatting doesn't transfer over from my word processor. Anyway, basically what I need to do is to get rid of coin2 so I can possibly make a new coin2 in the future. Is this possible even? If so how do I delete the object? (I'm guessing garbage collection, but I don't know how to do that.) Thanks.
class coin {

double money = 10;
String examine = "Lovely money!";

void displayMoney() {
System.out.println(money);
}


public static void main(String[] arguments) {
coin coin = new coin();

coin coin2 = new coin();

coin2.money = 5;

coin.money = coin.money + coin2.money;

/*This is where (I believe) some garbage collection should be done to get rid of my object (coin2). If I don't delete coin2 before I make a second coin2 object, the compiler spits out an error.*/

coin.displayMoney();
coin coin2 = new coin();
coin2.displayMoney();
}
}

2007-03-24 16:28:45 · 3 answers · asked by Invader Z 1 in Computers & Internet Programming & Design

By the way, I'm using Java. Don't miss this otherwise no one will know what I'm talking about!

2007-03-24 16:29:13 · update #1

I guess the formatting DID carry over. Yay! ^_^

2007-03-24 17:23:30 · update #2

Thank you all so much, it worked!

2007-03-24 17:36:26 · update #3

3 answers

The error has nothing to do with GC (and indeed you can't directly control when an object gets deleted), you're redeclaring coin2. When you create the second coin, just say "coin2 = new coin()" not "coin coin2..." since trhe coin2 variable already exists at that point.

2007-03-24 16:43:43 · answer #1 · answered by undercoloteal 3 · 0 0

The problem is that you are declaring 2 times coin2, you should write only coin2=new coin() the second time.
One more recommendation: Don't use class names for var names: instead coin coin=new coin() use coin coin1=new coin()

2007-03-24 23:54:16 · answer #2 · answered by Anonymous · 0 0

the first and second answer are all correct..
by the way.. if you insist want to use garbage collector (not advisable)

coin2 = null;
System.gc();
coin2 = new coin();

2007-03-26 02:18:21 · answer #3 · answered by Liviawarty J 2 · 0 0

fedest.com, questions and answers