but I have to create object of "pizzaMenu" in "main" to make it work.
Yes, you need an instance of new PizzaMenu()
in order to access that menu's items.
I'm having problem understanding "static".
Nothing in PizzaMenu
should really be static
(other than main
, if you have it there). But, it basically mean it belongs to the class, and not any one instance of that class.
In other words, if you did make the list of pizzas static
, then that says that all menus have the same pizzas, which shouldn't be true, right? Different places have different menus.
Here's an example.
public class PizzaMenu {
private List<String> pizzas = new ArrayList<>();
public void add(String name) {
pizzas.add(name);
}
public List<String> getPizzas() {
return pizzas;
}
// You can also move this to another class
public static void main() {
PizzaMenu menu = new PizzaMenu();
menu.add("Cheese");
for (String pizza : menu.getPizzas()) {
System.out.println(pizza);
}
}
}
All pizzas are added within that class, and it shouldn't be modified later.
You can use this, for example
private final List<String> pizzas = Arrays.asList("Cheese", "Pepperoni");
But, again, I think different instances of menus should have different pizzas.