This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The reference says that x on line 2 is not the same as x on line 4 and that's what I'm curious about. main() is a static method. Does that mean that x on line 4 is a static variable? I was taught that static members have no knowledge of any instance so if that's the case how can you even put a constructor inside a static method as shown above? I can see that it all compiles but it seems like a big contradiction to the separation of instances and statics. Line 5 has a constructor and line 8 has an instance initializer block which runs every time an instance is created right? If that's the case then x should be 4 by the time you compile line 5. Finally you hit line 6 and there is a preincremented x within. Is that x a local variable?
1. At line 2 you are defining a class instance variable called x.
2. At line 4 you are defining a method local variable called x.
3 At line 5 you are not "putting a constructor inside a method". You are creating an instance of Banana. static methods can create object instances.
4. You have no static variables.
5. Instance initializer blocks execute at runtime - not at compile time..
6. I assume you mean line 10 when you talk about the "preincremented x". That is incrementing the class instance x (line 2). The go() method does not have access to the local variable in main(). It only has access to the class instance x.