• Post Reply Bookmark Topic Watch Topic
  • New Topic

constructor running but not having a lasting effect  RSS feed

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd been wondering why no one was replying to my post asking this on Friday. Because I hadn't actually posted it might be a reason....

Anyway, so I 've written a class which should generate objects which take steps to run a session of a game. To test my code, I wrote a little class with a static main thread which would just try things out and print results. The constructor and fields for the game running class look like this:

and the little test program is

So, if you follow my thinking (and assuming addplayer does what its name implies), it seems that the output should be something like

foo 1
purple 1
true
4
true
Jon
Fred
Susan
Mark

But instead, the output is

foo 1
purple 0
false
3
false
Fred
Susan
Mark


So... am I missing something obvious? Why does the testing program output a value of 1 for game.numberOfPlayers=0 when the constructor set numberOfPlayers=1?

Any ideas?
 
Sheriff
Posts: 22845
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
J R Hatch wrote:So... am I missing something obvious? Why does the testing program output a value of 1 for game.numberOfPlayers=0 when the constructor set numberOfPlayers=1?


I guess it isn't obvious, because a lot of Java beginners do the same thing. Your constructor assigns 1 to a local variable named "numberOfPlayers". It leaves the instance variable "numberOfPlayers" untouched because the local variable hides that.

So don't declare those local variables in your constructor. What you did for "playerList" is the right thing to do.
 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because this line:

is creating a variable named numberOfPlayers in the constructor which occludes the instance variable.

[Edit: beat by 20 seconds!]
 
J R Hatch
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:
J R Hatch wrote:So... am I missing something obvious? Why does the testing program output a value of 1 for game.numberOfPlayers=0 when the constructor set numberOfPlayers=1?


I guess it isn't obvious, because a lot of Java beginners do the same thing. Your constructor assigns 1 to a local variable named "numberOfPlayers". It leaves the instance variable "numberOfPlayers" untouched because the local variable hides that.

So don't declare those local variables in your constructor. What you did for "playerList" is the right thing to do.


You and Bear are awesome except for making me feel dumb. Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!