Reputation: 121
I am new to Java and trying to learn it. I wrote two class as follows, and I expect to print as 1, 2, 3 but it prints 3, 3, 3. I read a java book about I couldn't figure out the above behavior and print 1, 2, 3.
public class Student{
private static int indexNumber = 0;
Student(){
indexNumber=indexNumber+1;
}
public void test() {
System.out.println(this.getIndexNumber());
}
public int getIndexNumber(){
return indexNumber;
}
}
public class College {
public static void main(String args[]){
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
student1.test();
student2.test();
student3.test();
}
}
Can anyone help?
Upvotes: 1
Views: 136
Reputation: 1
Since you have declared the INDEX NUMBER as static, therefore it will be shared by every instance you create for the class. The answer which you were expecting will come in the case you remove the static keyword. That's why for all three objects you get the same value for index number. I hope it's clear to u now. Thank you.
Upvotes: 0
Reputation: 331
Static members are shared with all objects. You not indexed, you counted with your test.
Upvotes: 0
Reputation: 3186
indexNumber
is declared as static
and its common to all objects. Hence you got 3,3,3
Static members are associated with the class, rather than with any object.
Upvotes: 2
Reputation: 179422
indexNumber
is static, so it's "shared" between every instance of the class.
If you want a unique, incrementing ID, do the following:
static int nextID = 1;
int indexNumber;
Student() {
indexNumber = (nextID++);
}
This makes indexNumber
an instance field, so that each Student
gets its own copy. The static variable is used to keep track of the next ID to be assigned.
Upvotes: 6
Reputation: 2274
Your field is static.It will be shared by all objects.
private static int indexNumber = 0;
s1-------->indexNumber<------s2
^
|
|
|
s3
Instantiating each time,the constructors gets called,which increments the indexNumber by 1.
Upvotes: 2
Reputation: 997
You get 3,3,3 because you have defined the variable indexNumber as static. So when instantiating three student objects the indexNumber gets value 3. To increment define the indexNumber as instance variable and pass the value for it as parameter.
Upvotes: 2