• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

non-static variable error

 
Timothy Onggowasito
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Rob Spoor
Sheriff
Pie
Posts: 20745
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your nested classes aren't static. That means that each instance of Monster, Vampire and Dragon must have an enclosing instance of MonsterTestDrive.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Neil Cartmell
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
stupid me!
I can't bealive I spent 20 minutes staring at this code finding nothing.

Thanks to all three of ya!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic