The title might be a mess, but I don't know how to describe it better.
Basically, let's say that I have an abstract superclass, let's say Person
that contains name, age and ID, and another class that extends from Person
, Members
.
I want to have a local variable in Members
that stores how many objects were created from this class, and assign it to the ID variable.
I.E.
I created two objects from Members
, m and m1. I want to automatically assign their ID for them, which increments by 1 each time an object is created.
Members m = new Member("Name");
Members m1 = new Member("Name2");
Then I call the method that prints the ID, two times for each object.
m's ID is 1.
m1's ID is 2
I went about to make this by having a local variable, int numberOfObjects = 1;
and objectID;
, and tried to make a new method
SetNumber()
{
objectID = numberOfObjects;
numberOfObjects++;
}
But, every time I make a new object, and call the method that shows it's ID, it sets it back to one.
So, can I make a local object, that doesn't reset every time I create a new object? Thanks.
I just needed to add static before the variable name. Thanks to turing85 for the answer. https://stackoverflow.com/users/4216641/turing85
Other answers were insightful, too.