Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with global variables

 
Alix Ollivier
Ranch Hand
Posts: 71
Java Linux Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to rewrite a tutorial for slick2d in my own way, but I've met a block. I want to use this code in a void method, while sheet is declared in another class. Is this possible? It says sheet cannot be resolved. I'm on Eclipse. Thanks in advance.

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll need to pass sheet to your method. Methods can't automatically see member variables defined in other classes.

Maybe this is an indication that you should be thinking more about the design of your classes. Think about which classes you have, and which methods belong in which classes.
 
Campbell Ritchie
Sheriff
Posts: 48448
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That isn’t a global variable. It is a private field in another class. You should avoid global variables like the plague, but if you are trying to get a field from another class, you should reconsider your design.
It might be appropriate to give that other class a getSheet() method, or getSpritesFromSheet(), but I don’t know enough about your application to tell that sort of thing. Don’t give the field more visibility in order to placate the compiler.
 
Alix Ollivier
Ranch Hand
Posts: 71
Java Linux Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sheet is a SpriteSheet, a .png with many sprites on it. I want to only load one, to make my game load faster and to keep all the assets in one location. Each entity that I will make hopefully will have an public void init() method in which the class initializes all of the variables and assets needed. The method below allows my player class to initialize where his sprites are.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic