Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static shamatic

 
Greg Neef
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?:
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic