when i run this code it print twice 0 but i don't undrestand why after affect the object k to null the value of count still printed 0 but when i delete static before count and rexecute this program it print first 0 and then i print an exception
Exception in thread "main" java.lang.NullPointerException
Please always tell us full details of where code or quotes come from; in this case, author's name(s) and page number. That reduces copyright problems and makes it easy to review the rest of the source. Only I probably don't have that book anyway.
I think it was a mistake in the language, but you are allowed to call static methods like this myObjectReference.someStaticMethod(). I think they should have restricted use of static members to ClassName.someStaticMethod(). But they didn't. You are referencing that static field from the type of the reference. The compiler thinks in line 5 that k is of type Koala, so it converts the call to Koala.count. When you get to line 7, it still thinks the type of the reference is Koala, so it still converts your call to Koala.count. You can even do something like this:- ((Arrays)null).sort(myArray); and you will get a sorted array and no exceptions. But it doesn't mean it's anything ike good programming. You can also get problems with trying to use a static method polymorphically. As you know, static methods are never polymorphic.If there is any difference between the static method in Car and that in Taxi, you get the Car's static method because its binding is static; it is fixed at compile‑time and doesn't change. The binding is static to the type, maybe that is why they chose the keyword static in the first place. Bound statically to Car, so you don't get the Taxi static method.
In line 4, the binding is dynamic and is done at runtime, so you get polymorphism, but that only applies to instance methods.
posted 1 month ago
Was the bad indentation in the code caused by your copying or was it that badly indented in the book? Remember that people who write cert exam practice questions often indent the code badly so as to make the question harder for learners to answer.
Whatever I said about access to static methods applies to static fields too when the usual rules about private and public are applied.