For example, I have this class named Member which basically creates a member who can log into a website. 5 things need to be initialised within the constructor whenever an instance of this object are made, one of them is the membership number. This membership number has to be unique. An idea I had was to add plus 1 to the number whenever a Member object is created.
Here is my current code:
public Member(String newEmail, int newMoney)
{
// Intialises the email.
email = newEmail;
// Intialises the membership number.
membershipNumber = 000;
membershipNumber =+ 001;
// Intialises the login status.
loginStatus = false;
//
companions = new ArrayList<Friend>();
// Intialises the members money.
money = newMoney;
}
Please ignore the loginStatus, companions and money.
As you can see i've set a default value for the membership number to be 000, and for +1 to be added onto it, but every member created, now matter how many I make, the membership number is always 1.
I tried another method by adding a whole other field like:
public Member(String newEmail, int newMoney)
{
// Intialises the email.
email = newEmail;
// Intialises the membership number.
membershipNumber = membershipNumberTwo;
membershipNumberTwo =+ 001;
// Intialises the login status.
loginStatus = false;
//
companions = new ArrayList<Friend>();
// Intialises the members money.
money = newMoney;
}
But the membership number is always 0.
Can anyone help me out by making the membership number have +1 added to it whenever the member is created in the constructor? Thanks.
Disclaimer: Im at beginner level of Java.
Why do this using numbers? Instead, create a unique membershipNumber using UUID. This will keep uniqueness and you don't have to work hard for that.
Have a look at the UUID class bundled with Java 5 and later.
use a random UUID you can use the randomUUID method.
Edit: If you plan to create the objects in concurrency and still want the incremental memberId, just store an static AtomicNumber and use atomicNumber.incrementAndGet() to get the 'new' userID
See more here
As for the examples you gave: In the 1st example - you initialise the value of membershipNumber within the constructor, which cause it always to be 1, like you described.
In the 2nd example, unless membershipNumberTwo
is static, it'll be initialised every construction of a new class, so every time it'll be initialised to 0. You need to keep state between construction of one object to the other.