I find hard to understand the following code taken from Sybex's first Mock Exam:
The code compiles and prints 30. Unfortunately, I thought that it wasn't going to compile due to the fact that the go() method is static whereas Car's member 'velocity' isn't.
How is that possible? Does the whole “non-static can access static and non-static but static can only access static” limits to members of the same class?
In any case, the exam's question is (at least for me) really tricky! I'm glad I found it in a mock exam instead of the real one.
If it just said velocity += 10; you would have the problem you mentioned about accessing a non-static variables.
You could move the go() method to another class and it would still compile for that matter. The fact that it is in the Car class at all is a happy coincidence. Or an evil trick .
Tomas Castagnino wrote:I get it! I suppose that's the same reason why we need to instantiate a class in order for the non-static methods' call from inside main() to compile in some classes.
Tomas Castagnino wrote:By the way, Jeanne, I think I there is an erratum in the errata: in the errata list the typo in page 111 (AnimAl) appears fixed when it actually isn't (I believe I have the second printing of the book and it's still "Animal").
I have a copy of the second printing and it looks right to me.