Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing instance-variable of another class without directly referring to the instance?

Why does this code print 2 and not 1?

The System.out is using A.i not a.i (in which case it would make sense to get the instance value of i = 2 since it would be using the instance a).

class A {
    static int i = 1;
    {i = 2;}
}

class B {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(A.i);
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This line in class A

{i = 2;}

is called an "initialization block" (some good discussion about them here). It is very similar to a constructor, in that the code in that block will be executed when a new instance is created. There is more to it than that, but for the purpose of your question, that’s really all you need to know.

So when you create a new instance of class A, that block runs, and it sets the (static) field i to the value 2. Since i is static, there is only ever 1 value, which is always set to 2.

Perhaps you mean for i to be an instance field? If so, remove the static modifier from its declaration. Note that even if you do that, i will still have the value 2 since the initialization block runs after the inline inialization.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading