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:
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.
I was going to say that line 6 outputs "0" and then line 8 outputs "0", which adds up to twice. But I see you posted something which already says that. So I'm not clear on what part of it is confusing you.
Don't worry; you aren't alone. This is one of the questions, asked often by new programmers or new Java programmers.
Only one copy of a static variable exists, which is shared by all the instances of that class. When a class is loaded in memory by Java Virtual Machine (JVM), a class's static variables are also made accessible. So you don't need instances of a class to access its static members. You can use a class name to access its static variables.
Accessing static variables is confusing at times because Java allows usage of both - class name and an instance variable, to access a static variable.
For example, for the following class:
You can access the static variable, by using the class name (that is, Book) or by using the name of its instance variable (refVar):
All calls to System.out.prinltn() in the preceding code, will output 'Comic'.
If you understand the above explanation, answer these question for me:
1) Why is the 'main' method in an executable class, defined as a static method?
2) Who calls this 'main' method?