Question about Java Enums

I have 2 files that interact with each other. I would like to define an enum to make the code more readable, but if I define it in file 1, file 2 complains that it does not know about this enum. If I define ii in file 2, file 1 does the same. I define him as an audience too.

The solution was to define the enumeration in both files, but this does not seem right to me. This is not only redundant, but I am afraid that this may cause some conflict, even if the types have the same elements.

What is the verdict on this? Am I doing something wrong or too worried?

EDIT

Well, given the comments here, I found an alternative that seems to do what I want without creating a new file. I have had:

file 1

class myClass1
{
    public enum MyEnum
    {
        ...
    }
    ...
}

file 2

class myClass2
{
    public enum MyEnum
    {
        ...
    }
    ....
}

Now I have:

file 1

enum myEnum
{
    ...
}

...

class myClass1
{
     ...
}

file 2

class myClass2
{
     ...
}

, . , , , .

+3
4

. . . , , , ...

import . , com.stackoverflow, : :

package com.stackoverflow;

public class A {
    public enum MyEnum {
      ONE,TWO,THREE;
    }

    ...
}

:

package com.stackoverflow;

import com.stackoverflow.A.MyEnum;

public class B {

  public void test(MyEnum mine) {
    ...
  }

  ...
}
+11

- . enum

public class MyClass {
    public static enum MyEnum { BOOK, DVD }


    public void myMethod() {
        MyEnum e = MyEnum.DVD;
    }
}


public class B {
    public void someMethod() {
        MyClass.MyEnum enumVal = MyClass.MyEnum.BOOK;
    }
}
+3

, u enum , - . ... , .

+1

, - , ( , ).

The definition of your enumeration in 2 files is violated, since this is a kind of victory for the goal - you will have 2 separate enumerations, and while you want to check the equality on Enum.A, you really will have Enum1.A! = Enum2.A. Very embarrassing.

There is no real secret for them, it's just a subtlety around defining constants that are safer and more capable than public static final ones.

0
source

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


All Articles