File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Problem with global variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem with global variables" Watch "Problem with global variables" New topic
Author

Problem with global variables

Alix Ollivier
Ranch Hand

Joined: Jun 04, 2012
Posts: 71

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.



"The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!', but 'That's funny...' "
- Isaac Asimov
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14435
    
  23

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
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

Joined: Jun 04, 2012
Posts: 71

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with global variables