Java - static link to list of non-static fields

I just experimented and found that when I run the rolling code, it does not compile, and I cannot understand why.

My IDE says, “It is not possible to make a static link to a non-static list of fields,” but I don’t quite understand what the reason is. Also what does this apply to, i.e. Are these just private variables and / or methods 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 works:

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);
    }

}
+5
source share
2 answers

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

Example:

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

, , .
tireMax, , ( ) .

, , , list MyList. , , list .

+4

, . ext MyList, .

0

All Articles