File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes non-static variable error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "non-static variable error" Watch "non-static variable error" New topic
Author

non-static variable error

Timothy Onggowasito
Greenhorn

Joined: Apr 16, 2010
Posts: 11
Hello, Ranchers

I went back few pages from the headfirst java book and tried a couple of excercise there.
On page 193 I tried to compile the correct code in the excercise on the compiler and I got:
non-static variable this cannot be referenced from a static context

The code is:


How do you make the following static?

Monster [] ma = new Monster[3];
ma[0] = new Vampire();
ma[1] = new Dragon ();
ma[2] = new Monster ();

I tried adding static in the beginning of each and that didn't work

Thanks in advance!

Apparently, what you don't know can hurt you...
Tim Ong
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

Your nested classes aren't static. That means that each instance of Monster, Vampire and Dragon must have an enclosing instance of MonsterTestDrive.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

That's because the mosters are inner classes of MonsterTestDrive thus can only be created with an instance of the enclosing class.
Creating an instance of MonsterTestDrive and then creating the monsters with that instance would be a solution but a better one would be to move the monster classes outside of the MonsterTestDrive class.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Neil Cartmell
Ranch Hand

Joined: Feb 13, 2010
Posts: 150
I'm looking at the code in Head first java and you've got one curly brace in the wrong place. That's what is causing you trouble.
Timothy Onggowasito
Greenhorn

Joined: Apr 16, 2010
Posts: 11
stupid me!
I can't bealive I spent 20 minutes staring at this code finding nothing.

Thanks to all three of ya!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: non-static variable error