wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes going bananas with this one Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "going bananas with this one" Watch "going bananas with this one" New topic
Author

going bananas with this one

Marcus Deviln
Ranch Hand

Joined: Jan 29, 2009
Posts: 39

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?



code sample courtesy of tmn.sun.com


+Deviln+ The power of JAVA compels you!
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
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.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40034
    
  28
Read this.

Get Campbell's requisite set of hardware, as recommended to our undergraduates. Pencil paper and rubber/eraser. The last is by far the most important
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: going bananas with this one