user1836386
user1836386

Reputation: 57

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??

Upvotes: 0

Views: 49

Answers (4)

Submersed
Submersed

Reputation: 8870

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

Upvotes: 0

kmera
kmera

Reputation: 1745

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.

Upvotes: 0

Filipp Voronov
Filipp Voronov

Reputation: 4197

Because p is static, i.e. 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.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240900

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

Upvotes: 4

Related Questions