Netbeans:访问静态字段 - 替换为类引用
在我的代码中,我有这样一行:
private static ArrayList<Item> items = new ArrayList<Item>();
然后我像这样定义了我的 setter 函数
public void setItems(ArrayList<Item> items) {
this.items = items;
}
NetBeans 抱怨 访问静态字段项,替换为类引用?
如果我将此调用替换为类引用,如 MyClass.items = items;
它不会传播到当前对象中,不是吗?
In my code I have this line:
private static ArrayList<Item> items = new ArrayList<Item>();
and then I defined my setter function like this
public void setItems(ArrayList<Item> items) {
this.items = items;
}
And NetBeans complains Accessing static field items, replace with class reference?
If I would replace this call with class reference like MyClass.items = items;
it wouldn't be propagated into current object, isn't it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
静态变量永远不会“传播”到“当前”对象中。
它是静态的,绑定到类。即使没有类的实例,它也存在,因此不需要“传播”它。
顺便说一句:我会更改方法参数的名称,在方法内两次使用相同的名称会令人困惑(如果参数的命名方式不像静态变量那样,则不需要 this :
A static variable is never "propagated" into the "current" object.
It is static, bound to the class. It lives even without an instance of the class, so there is no need to "propagate" it.
Btw: I would change the name of the method parameter, it is confusing to have the same name twice inside a method (and you wouldn't need the this if the parameter wasn't named like the static variable:
一旦您将类中的成员声明为
static
,那么它就属于该类。也就是说,它只会在创建第一个对象实例时定义一次。即将存储在类的堆栈中。
其余类的所有实例将共享该成员变量。
当声明非静态变量时,每当我们为该类创建对象时,都会为该变量分配单独的内存,该内存特定于该实例。
在这种情况下,
private static ArrayList- items = new ArrayList
- ();
是类的成员变量。虽然您可以使用
this
访问变量,但它会造成混乱。this
用于实例变量,而静态成员变量则通过类名本身访问。我希望这能消除疑虑。
Well once you have declared a member in your class as
static
then it belongs to the class.That is it will be defined only once when the first object instance is created. That is will be stored in the stack of the class.
Rest all the instances of the class will share the member variable.
When a non-static variable is declared, whenever we create the object for that class a separate memory will be allocated for that variable, which will be specific to that instance.
In this case the
private static ArrayList<Item> items = new ArrayList<Item>();
is the member variable of the class. Although you can access the variable using
this
but it creates a confusion.this
is used in case of instance variable whereas static member variables are accessed through the Class name itself.I hope this clears the doubt.
我不确定您是否希望
items
是静态的。静态属性意味着该变量是全局的。如果您希望每个对象都有自己的
items
实例,则必须删除static
修饰符。I'm not sure if you want
items
to be static. A static property means that the variable is sort of global.If you want each object to have their own instance of
items
you'll have to remove thestatic
modifier.