Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 339
mino Avatar asked Oct 09 '22 02:10

mino


1 Answers

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.

like image 93
Jean-Bernard Pellerin Avatar answered Oct 13 '22 10:10

Jean-Bernard Pellerin