Java에서 상수 클래스를 어떻게 정의합니까? (How do you define a class of constants in Java?)


문제 설명

Java에서 상수 클래스를 어떻게 정의합니까? (How do you define a class of constants in Java?)

상수를 유지하는 클래스를 정의해야 한다고 가정합니다.

public static final String SOME_CONST = "SOME_VALUE";

이 작업을 수행하는 데 선호되는 방법은 무엇입니까?

  1. 인터페이스
  2. 추상 수업
  3. 최종 수업

어떤 것을 사용해야 하며 그 이유는 무엇입니까?


일부 답변에 대한 설명 :

열거형 ‑ 열거형을 사용하지 않을 것입니다. 아무 것도 열거하지 않고 어떤 식으로든 서로 관련이 없는 일부 상수를 수집할 뿐입니다. .

인터페이스 ‑ 인터페이스를 구현하는 클래스로 설정하지 않겠습니다. ISomeInterface.SOME_CONST와 같이 인터페이스를 사용하여 상수를 호출하기만 하면 됩니다.


참조 솔루션

방법 1:

Use a final class. for simplicity you may then use a static import to reuse your values in another class

public final class MyValues {
  public static final String VALUE1 = "foo";
  public static final String VALUE2 = "bar";
}

in another class :

import static MyValues.*
//...

if(variable.equals(VALUE1)){
//...
}

방법 2:

Your clarification states: "I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way."

If the constants aren't related to each other at all, why do you want to collect them together? Put each constant in the class which it's most closely related to.

방법 3:

My suggestions (in decreasing order of preference):

1) Don't do it. Create the constants in the actual class where they are most relevant. Having a 'bag of constants' class/interface isn't really following OO best practices.

I, and everyone else, ignore #1 from time to time. If you're going to do that then:

2) final class with private constructor This will at least prevent anyone from abusing your 'bag of constants' by extending/implementing it to get easy access to the constants. (I know you said you wouldn't do this ‑‑ but that doesn't mean someone coming along after you won't)

3) interface This will work, but not my preference giving the possible abuse mention in #2.

In general, just because these are constants doesn't mean you shouldn't still apply normal oo principles to them. If no one but one class cares about a constant ‑ it should be private and in that class. If only tests care about a constant ‑ it should be in a test class, not production code. If a constant is defined in multiple places (not just accidentally the same) ‑ refactor to eliminate duplication. And so on ‑ treat them like you would a method.

방법 4:

As Joshua Bloch notes in Effective Java:

  • Interfaces should only be used to define types,
  • abstract classes don't prevent instanciability (they can be subclassed, and even suggest that they are designed to be subclassed).

You can use an Enum if all your constants are related (like planet names), put the constant values in classes they are related to (if you have access to them), or use a non instanciable utility class (define a private default constructor).

class SomeConstants
{
    // Prevents instanciation of myself and my subclasses
    private SomeConstants() {}

    public final static String TOTO = "toto";
    public final static Integer TEN = 10;
    //...
}

Then, as already stated, you can use static imports to use your constants.

방법 5:

My preferred method is not to do that at all. The age of constants pretty much died when Java 5 introduced typesafe enums. And even before then Josh Bloch published a (slightly more wordy) version of that, which worked on Java 1.4 (and earlier).

Unless you need interoperability with some legacy code there's really no reason to use named String/integer constants anymore.

(by Yuval Adamuser54579Jon Skeetkenj0418Sébastien RoccaSerracletus)

참조 문서

  1. How do you define a class of constants in Java? (CC BY‑SA 2.5/3.0/4.0)

#class-constants #java






관련 질문

NDK: 자바 클래스에서 .c 상수를 사용하는 방법 (NDK: How to use .c constants in java class)

상수 클래스 멤버, 할당 연산자 및 QList (Constant class members, assignment operator and QList)

kotlin 클래스의 상수 풀에 있는 미친 UTF-8 항목 (Crazy UTF-8 entry in a kotlin class' constant pool)

PHP 5.3 ~ PHP7 - 정의되지 않은 클래스 상수 'self::MYCONST' (PHP 5.3 to PHP7 - Undefined class constant 'self::MYCONST')

PHP의 특정 클래스에 정의된 '클래스 상수'와 함께 defined() 메서드를 사용하는 방법은 무엇입니까? (How to use defined() method with 'Class Constants' that are defined into a specific class in PHP?)

클래스 상수를 사용한 PHP 객체 액세스 (PHP Object access with class constant)

Java에서 상수 클래스를 어떻게 정의합니까? (How do you define a class of constants in Java?)







코멘트