NOT_A_PROGRAMMER
NOT_A_PROGRAMMER

Reputation: 1924

Use Interface or Class for Constants?

There is a lot of negative comments about using interface for constants in Java. I just want to know for Android development if it is the same, and the reason why. I have this question because I heard the battle between Enum and static final. Enum is not a good thing for Android development, and I found a YouTube video post by Android Developer that suggests developer to use static final instead of Enum.

Upvotes: 1

Views: 271

Answers (3)

Ch1pCh4p
Ch1pCh4p

Reputation: 46

It depends on what you are trying to do. If you need to store a collection of typesafe static data, then use enums. For example, you might use a collection of coin types for representing currency.

Like this:

 public enum Coin {
     PENNY,
     NICKEL,
     DIME,
     QUARTER;
 }

For static data that is not of the same type, use static final values.

For example:

static final int FREEZING_TEMP_FAHRENHEIT = 32
static final double GRAVITY = 9.81

It depends on if you can group that static data such that it should be stored as a collection of things. If so, enum. If not, static final.

Upvotes: 3

chosendeath
chosendeath

Reputation: 106

For constants I generally create a resource for it. For strings for example you would use strings.xml, you can have integer constants as well. This method is useful because you abstract your content from your code which I feel is more organized. For constants needed for a specific class I would keep them scoped inside the class though!

Upvotes: 0

marktani
marktani

Reputation: 7808

What do you mean by interface for constant? In most of my apps I have a Singleton class Constants that has some public static final field (stuff that is known at development time) and some public fields (stuff that is only known at runtime and is initialized when the singleton instance is initialized by the first call to Constants.getInstance()). If some of my fields need a context to be set, usually I add a method initialize(Context context), that is the first thing I call in MainActivity's onCreate.

Upvotes: 1

Related Questions