• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why can't I make public variables in void methods?  RSS feed

 
Alix Ollivier
Ranch Hand
Posts: 71
Java Linux Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone. I am trying to use Slick2d to make a game, and I have a trouble initializing variables. I am using the BasicGame class to make my game. This class has three methods: init(), update(), and render(). init() is where I initialize variables. However, when I try to initialize a variable like this:

It doesn't work. However, when I put the SpriteSheet outside the init() method, it works. Why is that?
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variables which are declared inside methods (void methods or otherwise) are local to that method. In other words, they can't be accessed by any code outside the method.

That being the case, it doesn't make sense to declare them public, since the "public" modifier is specifically about how code outside the class can access the variable. It only makes sense to declare class-level variables to be public, as in your second example.
 
Alix Ollivier
Ranch Hand
Posts: 71
Java Linux Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah. Thanks Paul.
 
Ritesh raushan
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok please also explain why we don't use private,protected,static and all other keyword except final keyword in local variable.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ritesh raushan wrote:ok please also explain why we don't use private,protected,static and all other keyword except final keyword in local variable.

Ritesh. Please don't ask your own questions in other people's threads. It's called "hijacking", and it's considered bad form (on almost any site).

If you have a question, create a thread of your own. Just look at the FAQ pages; it's very simple.

Thanks.

Winston
 
Campbell Ritchie
Marshal
Posts: 56585
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For exactly the same reason as you can’t say public.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:
Ritesh raushan wrote:ok please also explain why we don't use private,protected,static and all other keyword except final keyword in local variable.

Ritesh. Please don't ask your own questions in other people's threads. It's called "hijacking", and it's considered bad form (on almost any site).


Besides which the question was just answered right here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!