Java 通过引用类避免访问静态字段?

Java 通过引用类避免访问静态字段?,java,static,class-reference,Java,Static,Class Reference,我不明白为什么这是工作,请帮助教育我 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:"

我不明白为什么这是工作,请帮助教育我

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));
我初始化对象CFIG,它设置类Config tileGallery ArrayList和featureGallery ArrayList的成员变量。当我运行代码时,它会工作,输出选定的测试值。但是,对于这两个声明性语句,Netbeans都会发出访问静态字段的警告

使用Replace with class reference的提示,它将语句更改为:

Tile selectedTile = Config.tileGallery.get(1);
Feature selectedFeature = Config.featureGallery.get(3);
当我运行它时,它仍然工作

问题,配置。未标识从哪个配置对象调用数据。现在我只有一个配置对象存在,但即使我初始化了第二个配置对象,它仍然不会出现混乱

这是怎么回事

编辑:安迪想知道配置类的代码是什么。我没有添加它,因为它不多,并且我认为你可以很容易地假设它是如何做的,因为它涉及到这个问题。然而,它就在这里,以防万一

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

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

static关键字表示此字段属于类而不是类的实例。即使创建了100个对象,此字段也将在其中共享。 来自每个实例的这些静态字段tileGallery和featureGallery将指向内存中的同一对象


静态变量在类加载时只在类区域中获取一次内存。

如果没有配置类的确切代码,很难说,但看起来您的配置类使用了如下静态字段

   public class Config {
      public Config() { 
         titleGallery = new ArrayList();
         titleTallery.add(new Title());
      }

      public static List<Title> titleGalery;
    }

为什么它不能工作?一个静态变量在该类的所有实例之间共享。如果tileGallery应该绑定到Config类的特定实例,则使用静态访问说明符。问题是,在将所有语句更改为使用Config而不是CFIG之后,将显示一个新的警告,其中只显示“引入…”。。。Alt+Enter不提供任何其他信息。再次感谢那些提供答案的人,我从中学到了一些东西!我认为这意味着不同的东西=
public class Config {
      public Config() { 
         titleGallery = new ArrayList();
         titleGallery.add(new Title());
      }

      // old: public static List<Title> titleGalery;
      public List<Title> titleGalery;
    }