Java - making a static reference to the non-static field list

耗尽温柔 提交于 2019-12-01 03:34:07

问题


I've just been experimenting and found that when I run the rolling code, it does not compile and I can't figure out why.

My IDE says 'Cannot make a static reference to the non-static field list', but I don't really understand what or why this is. Also what else does it apply to, i.e.: is it just private variables and or methods too and why?:

public class MyList {

    private List list;

    public static void main (String[] args) {
        list = new LinkedList();
        list.add("One");
        list.add("Two");
        System.out.println(list);
    }

}

However, when I change it to the following, it DOES work:

public class MyList {

    private List list;

    public static void main (String[] args) {
        new MyList().exct();
    }

    public void exct() {
        list = new LinkedList();
        list.add("One");
        list.add("Two");
        System.out.println(list);
    }

}

回答1:


static fields are fields that are shared across all instances of the class.
non-static/member fields are specific to an instance of the class.

Example:

public class Car {
  static final int tireMax = 4;
  int tires;
}

Here it makes sense that any given car can have any number of tires, but the maximum number is the same across all cars.
If we made the tireMax variable changeable, modifying the value would mean that all cars can now have more (or less) tires.

The reason your second example works is that you're retrieving the list of a new MyList instance. In the first case, you are in the static context and not in the context of a specific instance, so the variable list is not accessible.




回答2:


In the first example you are calling non-static field from static content, which is not possible. In the second one you are calling ext function on MyList object, which has access to that field.



来源:https://stackoverflow.com/questions/10200740/java-making-a-static-reference-to-the-non-static-field-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!