aspose file tools*
The moose likes Beginning Java and the fly likes static shamatic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static shamatic" Watch "static shamatic" New topic
Author

static shamatic

Greg Neef
Ranch Hand

Joined: Jun 16, 2003
Posts: 82
ok, i read that 'static' means only one per class. sounds reasonable. But, why can't I do:

without getting the error about a non-static reference in a static context. Seems like all the idiot level examples in the books I am looking at assume that you can.
So, to get around this annoyance i have been doing this:

which stops the compiler bitching. Which is all well and good, except if static means one per class, why can i do this?:


SCJP 1.4
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Static means more than one-per-class. Static really means that the member is not polymorphic. The implication of that is that the compiler will insist that all information be available for linkage at compiletime. Contranst that with an instance member (especially methods) which are bound (or linked) at runtime. Now with that in mind it becomes clear why you cannot directly create an instance of an inner class from a static context, because in order to create an inner class you must have an instance of the enclosing class. In a runtime environment you could have hudreds of instances of Foo, so which one does the compiler use (even if it had a crystal ball and would know how many there would be at runtime)? You can create an instance of Bar without making it static like this:


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

Greg, I guess you've just discovered the beauty of Inner Classes( whether you wanted to or not! ). Since you declared the Bar class within the Foo class, the Bar class can not exist without a Foo class. So you can not have a Bar without a Foo first being created:
this is how it looks in java code:
You can read up on Getting in Touch with your Inner Class.
The other option is that you've stumbled upon inner classes by accident, and what you really want is 2 mutually exclusive classes in which you just have to move the Bar class outside of the Foo class braces:

Jamie
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static shamatic