简体   繁体   中英

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

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, ie: 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);
    }

}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM