File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Inheritance, and the mis-use of the 'static' keyword Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inheritance, and the mis-use of the Watch "Inheritance, and the mis-use of the New topic

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

Steve Jensen
Ranch Hand

Joined: Sep 23, 2002
Posts: 126
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.

John Bonham was stronger, but Keith Moon was faster.
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

If you have the code in one file, say, 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, it makes BoxWeight a top-level class that can be instantiated independently of Box and will compile and run.

[How To Ask Questions On JavaRanch]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Steve Jensen
Ranch Hand

Joined: Sep 23, 2002
Posts: 126
Yep, I've moved class BoxWeight to the top level - works a treat.
Cheers Folks!
I agree. Here's the link:
subject: Inheritance, and the mis-use of the 'static' keyword
It's not a secret anymore!