r/javahelp • • Jul 23 '20

Solved Need help understanding objects

Hello, the following code is given off a practice exam for our upcoming exam:

public class Main {
    public static void main(String[] args) {
        Test t = new Test();
        t.i = 200;
        System.out.print(Test.i + " " + t.i);
    }
}
class Test {
    public static int i;
    public Test() {
        i = 100;
    }
}

The question is asking for the output. The output is: 200 200

Why? I understand why t.i is 200, but why is Test.i 200? From my understanding, Test is the 'type' of an object. Does this mean that the variable i will change for every object of type Test? Is this because i is static, public, or both?

18 Upvotes

7 comments sorted by

14

u/sinistergroupon Jul 23 '20

Variable i is static which means it’s the same for any Test object. It’s shared. Since it’s static it can be referenced by class or through any instance of type Test.

1

u/cgjnm Jul 23 '20

Makes sense, thank you

2

u/VanVleet-goes-for-22 Nooblet Brewer Jul 23 '20

I asked this question about a month ago. You'll get a detailed answer here

1

u/cgjnm Jul 23 '20

Awesome, thank you! Do you know if Java would only replace the object with its class (while accessing static members) if the object is null, or does it get replaced in all cases? Like in my code above (i.e., would t.i get replaced with Test.i as well)

2

u/VanVleet-goes-for-22 Nooblet Brewer Jul 23 '20

Yes, static members will always look at the class type , not the object. In your code, t.i is equivalent to Test.i because the class type for t is Test.

1

u/cgjnm Jul 23 '20

Awesome, thank you for the help and explanation

-1

u/Python119 Jul 23 '20

Objects are like variables that have multiple values, all of which can be different data types