Forums Register Login

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

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Yep, I've moved class BoxWeight to the top level - works a treat.
Cheers Folks!
After some pecan pie, you might want to cleanse your palatte with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1196 times.
Similar Threads
cannot find symbol - constructor error while extending a class
Return Statements
End of file while parsing
can we invoke an overloaded constructor by object of same class?
static reference to nonstatic var & methods
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 09:30:21.