简体   繁体   中英

Unusual behavior of java program

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?

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.

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.

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.

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.

Static members are shared with all objects. You not indexed, you counted with your test.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM