开发者

Netbeans: accessing static field - Replace with Class reference

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 complain开发者_StackOverflow中文版s 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?


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:

public void setItems(ArrayList<Item> itemList) {
    items = itemList;
}


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.


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 the static modifier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜