Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
java object help?
Hey, I am writing a program and I am stumped. During the program I am creating several of the same type objects. I am trying to give each object it's own "reference number" I guess you could say. But, after all the classes are created, all of the objects have the same number assigned to them. This is an excerpt of what I am using when creating an object and assigning a number.
private static int Number = 0;
static int count = 0;
public xxx(){
this.Number = count;
count += 1;
}
It seems that all of the objects are going back and grabbing the last value of count and using that.
AHHH, thanks guys. Still trying to learn the ropes on this stuff. I REALLY appreciate the help. I racked my brains forever on this lol.
2 Answers
- 1 decade agoFavorite Answer
It's because you're using a static variable for your number. Static values are the same across all instances (objects) of the class.
What you want is to remove the static modifier from the "number" variable, but keep it for the "count" variable. That way, every object you instantiate will up the count by 1, but save off the current count to a private number variable.
- Anonymous1 decade ago
This is going to kill you - you declared the int count as 'static', which, by definition, means that it's value cannot be changed. So, for starters, you need to change it to public or private, and get rid of the static.
However, this may not completely solve the problem, as any time the class is called, it may reinitialize the 'count' value to 0. I think if I were you, I would add the objects to an arraylist in the procedure calling this class after instantiating them. That is what array lists are for. If you want, you could make some kind of property called 'referenceNumber' for the class, and increment it each time the class is called.
Good luck, and happy coding.