Hello fellow programmers!
I am preparing for the OCA
Java SE 8 Programmer I exam and to prepare for it I use the book by Jeanne Boyarsky and Scott Selikoff. However, I came upon some confusion. Here:
Calling a Static Variable or Method
Usually, accessing a static member is easy. You just put the classname before the method or variable and you are done. For example:
System.out.println(Koala.count);
Koala.main(new String[0]);
Both of these are nice and easy. There is one rule that is trickier. You can use an instance of the object to call a static method. The compiler checks for the type of the reference and uses that instead of the object—which is sneaky of Java. This code is perfectly legal:
5: Koala k = new Koala();
6: System.out.println(k.count); // k is a Koala
7: k = null;
8: System.out.println(k.count); // k is still a Koala
Believe it or not, this code outputs 0 twice. Line 6 sees that k is a Koala and count is a static variable, so it reads that static variable. Line 8 does the same thing. Java doesn’t care that k happens to be null. Since we are looking for a static, it doesn’t matter.
Above is a part of the book.
The problem is that I still don't get why the code outputs 0 twice. Please explain with detail.
Thanks,
Maxwell