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

∥☆過路亽.° 提交于 2019-12-01 05:40:36

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.

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