In java Class level variables are Object associated until unless they are not declared static
.
By means of Object associated is that when a object is initialized with new keyword in Java all Object will be having it’s own memory and own class variables.
In your case inside main method when you create a Object of Test
class and when you create a another test class object inside Test2 class, both will be totally independent of each other. And both will be having their own memory and own variables.
If you want that to get the updates of inventory
variables from first object to be available in another object you need to declare it as static and should be initialized inside static block. Static variables are shared across all objects of class. As below:
static ArrayList<String> inventory;
static {
inventory = new ArrayList<String>();
}
solved Unable to see ArrayList elements in another object in Java