Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

error: "cannot find symbol"

 
MR Chen
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

So, I've got this little piece of code:



When I compile, it gives me this error:



So, why does it accept the first reference to GameBoard, but not the second? I'm sure there's something fundamental I'm missing here...

Thanks,
Mike
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
method whoIsThere "GameBoard" cannot see the "GameBoard" that is declared in the constructor.


would allow gameBoard to be visible from both the constructor and the whoIsThere method.

(Convention is that variable and method names should begin with lower case while class names begin with upper case.)
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by MR Chen:
... I'm sure there's something fundamental I'm missing here...

Yes, it's an issue of scope, meaning where a variable is valid.

Your variable "GameBoard" is declared inside the body of the MyGame constructor, so its scope is limited to that constructor's body. Therefore, within the method whoIsThere, "GameBoard" is out of scope, and has no meaning.

I think you want to define this as an instance variable so that it's available everywhere in the object. If you wish, you can still value the variable in the constructor...

[ September 05, 2007: Message edited by: marc weber ]
 
MR Chen
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marilyn/marc - thank you for your quick replies. I'll have to keep this scope thing in mind...

I notice that both of you declared "gameBoard" outside of the constructor, but then valued it inside the constructor:


Is there any advantage to doing it that way, as opposed to just using

outside of the constructor?

Again - many thanks,
Mike
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did it that way to show that you can still value it from the constructor, if you wish. There are situations where that might be necessary -- for example, if the constructor is passed values that need to be used in constructing a GameBoard.

However, you can certainly initialize an instance variable at the point of declaration. Personally, I prefer this (when possible and practical) because it's a way of guarding against a null exception.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic