0

I created a class Test with 3 inner Objects of class Test.

pblic class Test
{
  public static final Test test1=new Test("a");
  public static final Test test2=new Test("b");
  public static final Test test3=new Test("c");

  //instance
  public static String instance;

 public Test(String init)
{
  instance=init;
}

.
.
.

This works so far. Than I have a enum file where I do this:

public enum myEnum
{
 APPLE{{this.enumtest=Test.test1}};

Test enumtest;
.
.
.

When I call enumtest.toString I receive the String of test3 not test1. I thought every inner class Object has it's own parameter instance but it seems that it gets overwritten till the lase object was created. Is there any way to solve this problem? Thanks

FishingIsLife
  • 1,972
  • 3
  • 28
  • 51

2 Answers2

2

Never do that. You write the value of the static variable inside the constructor. Obviously static variables are initialised in the natural order, so the last value written to the instance variable is that one from the test3.

To fix that you have to remove the static modifier from the variable instance.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
0

The problem is that you have declared your String instance as static. This means that it exists just once for the entire class, not once per instance. Remove the static and it should work as intended.

O.O.Balance
  • 2,930
  • 5
  • 23
  • 35