Java - 对非静态字段列表进行静态引用 [英] Java - making a static reference to the non-static field list

查看:243
本文介绍了Java - 对非静态字段列表进行静态引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进行实验,发现当我运行滚动代码,它不编译,我不能弄清楚为什么。

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.

我的IDE说'不能静态引用非静态字段列表',但我真的不明白什么或为什么这是。还有什么适用于,即:它只是私有变量和或方法太?为什么?:

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

}

以下是它的工作:

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.

示例:

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

这里有意义的是,任何给定的汽车可以有任何数量的轮胎,

如果我们使 tireMax 变量可变,修改该值将意味着所有汽车现在可以有更多(或更少)轮胎。

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.

第二个示例的原因是您正在检索列表新的MyList实例。在第一种情况下,您处于静态上下文中,而不是在特定实例的上下文中,因此不能访问变量 list

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.

这篇关于Java - 对非静态字段列表进行静态引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆