javastaticclass-reference

Accessing static field avoided by referencing Class?


I'm not understanding why this is working, please help educate me.

Config CFIG = new Config();
Tile selectedTile = CFIG.tileGallery.get(1);
System.out.println("This is the name:" + selectedTile.getName());
Feature selectedFeature = CFIG.featureGallery.get(3);
System.out.println("This is the name:" + selectedFeature.getName()+ 
    " " + selectedFeature.getEffect(0));

I initialize the object CFIG, which sets both the member variables of the Class Config tileGallery ArrayList and featureGallery ArrayList. When I run the code, it works, outputting the selected test values. However for both of the declarative statements Netbeans gives a warning of "Accessing static field "

Using the hint of "Replace with class reference", it changes the statements to:

Tile selectedTile = Config.tileGallery.get(1);
Feature selectedFeature = Config.featureGallery.get(3);

When I run it, it still works!

Question, Config. isn't identifying which Config object to call data from. Now I only have a single Config Object in existence, but even if I initialize a second Config object it still doesn't appear confused.

What's going on here?

EDIT: andih wondered what the code of the Config Class. I didn't add it, because it wasn't much, and figured you could easily assume what it did as it pertains to the issue. However, here it is, just in case.

public class Config {
    public static ArrayList<Tile> tileGallery;
    public static ArrayList<Feature> featureGallery;

    public Config (){
        this.tileGallery = Tile.ReadTileXML();
        this.featureGallery = Feature.ReadFeatureXML();
    }
}

Solution

  • Without the exact code of your Config class it's hard to say but it looks like your Config class uses static fields like

       public class Config {
          public Config() { 
             titleGallery = new ArrayList();
             titleTallery.add(new Title());
          }
    
          public static List<Title> titleGalery;
        }
    

    That's what the hint says.

    In this case all your Config instances share the same titleGalery and you can access them via Config.titleGalery.

    If you want different Configinstances with different value you'll have to remove the static keyword to get independent instance fields.

    public class Config {
          public Config() { 
             titleGallery = new ArrayList();
             titleGallery.add(new Title());
          }
    
          // old: public static List<Title> titleGalery;
          public List<Title> titleGalery;
        }