-1

I'm working on a big project, but for this question I write a simple example of the problem. I have 2 classes.

public class Main
{
    public static void main(String[] args)
    {
        CustomType[] customType = new CustomType[3];

        for(int i = 0; i < 3; i++)
        {
            customType[i] = new CustomType(i);
        }

        for(int i = 0; i < 3; i++)
        {
            System.out.println("Main " + customType[i].integer);
        }
    }
}

and

public class CustomType
{
    public static int integer;

    public CustomType(int input)
    {
        integer = input;
        System.out.println("CustomType: " + integer);
    }
}

I get the following output:

CustomType: 0
CustomType: 1
CustomType: 2
Main 2
Main 2
Main 2

but I want to get this:

CustomType: 0
CustomType: 1
CustomType: 2
Main: 0
Main: 1
Main: 2
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Gergő Gutyina
  • 129
  • 1
  • 12

3 Answers3

3

Your issue is because you're using a static variable for integer.

A static variable is common to all the instances of an object or class (in your case your CustomType class). Put simply, a single copy of your static variable is created and shared amongst all the instances of your class.

So when you create your CustomType object at index 0 of your for loop, the static variable value is 0 for all instances. When index position 1 of the array is used, it changes to 1 for all instances. When your for loop ends at index position 2, the static variable finishes with a value of 2 for all instances.

What you need to do, instead, is use: public int integer

This will give each CustomType object its own individual integer variable which will be assigned with the correct values that you are looking for.

AJC24
  • 3,280
  • 2
  • 19
  • 30
1

If you wanted to have different values for each object then don't make the variable static, rather set it to private and make a getter method to retrieve your private var.

This

 public static int integer;

to

 private int integer;

And your getter method will retrieve the data

public int getInt()
{
    return integer;
}
DPreme
  • 46
  • 3
0

static is the hint..

Why would you think a static variable would be bind to a specific instance in the first place?

Try using public int integer; instead of public static int integer; and look at the magic behind instance variables.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89