Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance, and the mis-use of the 'static' keyword

 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Folks, i've typed in a program used to illustrate some concepts used in inheritance, from a book. The thing is, there are 2 errors , and I think they are related to the fact that i'm referring to two non-static variables, within a static method:-

public static void main (String args[])
{
BoxWeight mybox1 = new BoxWeight (10,20,15,34.3);
BoxWeight mybox2 = new BoxWeight (2,3,4,0.076);


The full code listing is shown below. What grates me is that this code has been printed in text book, and therefore has errors in it (I think!).
Any help in solving this problem would be greatly appreciated. Cheers in advance.
code
 
Joe Ess
Bartender
Posts: 9279
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have the code in one file, say Box.java, then BoxWeight is an inner class of Box and can't exist outside of it, hence your static variable problem. If you take that code and put it into BoxWeight.java, it makes BoxWeight a top-level class that can be instantiated independently of Box and Box.java will compile and run.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only problem with this code (and it's possible that it's not a problem in the original -- you may have made slight transcription errors on typing it in) is that the class BoxWeight, which extends the class Box, is a nested class inside Box itself. This isn't illegal, but it's unusual, and the compiler needs a little clarification before it will compile correctly -- you're probably also seeing multiple error messages about "Ambiguous reference".
The errors about "static regions" mean that the BoxWeight objects need an enclosing outer instance. If you have no idea what that means, that's fine -- just follow the advice below to clear this up.
The example doesn't seem to have anything to do with nested classes, so the code will be easier for you to work with and understand if you hoist BoxWeight up to the top level: i.e. take all the lines

and move them to the very end of the file. The code will then compile without a hitch.
 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep, I've moved class BoxWeight to the top level - works a treat.
Cheers Folks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic