简体   繁体   中英

Java. Object instance changes weirdly

class Test {
    static int p;
    Test(int x) {
        p=x;
    }
}

class Mtest
{
    public static void main(String args[])
    {
        Test c[] = new Test [100];
        for(int i=0; i<5; i++) {
            c[i]=new Test(i);
        }

        for (int i=0; i<5;i++) {
            System.out.println(c[i].p);         
        }
}

OUTPUT: 4 4 4 4 4

What kind of sorcery is this? shouldnt it give me 0,1,2,3,4??

You are using static field

static int p;

which is shared across class (not per instance)

if you want it per Object, remove static from declaration

Because p is static, ie field of the class, not of an object. So p is shared between all instances of class test . You should remove static from field declaration to achieve your result expectations.

You declared p as static . Remove it and it should word fine. Plus format your code following the java guidelines, it makes it much more readable.

Change static int p; to int p -> You're using class variables instead of instance variables.

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