Enum supported by enum in Java

I created enumin Java, with each element enumreferencing a different one enum. I also took advantage of a receiver that will return the reference instance. I would say nothing strange or wrong. The only difference from the usual implementation enumis the use of another enumas a support value. I do not use intor any other primitive type.

Then I tried to implement the other enumin the same way and use the first enumas the base value for its elements. The code compiles fine and nothing seems to be wrong until I called the getter several times.

See for yourself in the next JUnit test. The statement fails on the last line.

Why is this failing?

import static org.junit.Assert.assertNotNull;
import org.junit.Test;

enum EN {
    DOG(CS.PES),
    CAT(CS.KOCKA);

    CS v;

    EN(CS v) {
        this.v = v;
    }

    public CS getCS() {
        return this.v;
    }
}

enum CS {
    PES(EN.DOG),
    KOCKA(EN.CAT);

    EN v;

    CS(EN v) {
        this.v = v;
    }

    public EN getEN() {
        return this.v;
    }
}

public class EnumTest {

    @Test
    public void testValueOfEnum() {
        String zvire = "PES";
        CS pes = CS.valueOf(zvire);
        assertNotNull(pes);
        assertNotNull(pes.getEN()); // OK
        assertNotNull(pes.getEN().getCS()); // FAIL -- getCS() is null
    }
}
+4

Source: https://habr.com/ru/post/1648246/


All Articles