Re: Where do you keep contants in Interfaces or in classes?



Stefan Ram wrote:
(1) Constants can only be kept in interfaces,

Which is known as the Constant Interface Antipattern. It's also not true.

classes might have »final fields« or »constant variables«, but these are not
called »constants« in Java.

Acxtually, they are, if they conform to the JLS's rules for what is called a "constant variable", which if statis is the same thing as a "constant".

JLS3, 4.2.4 mentions constants in classes:

»Other useful constructors, methods, and constants are
predefined in the classes Float, Double, and Math.«

I admit that this contradicts my previous statement (1). But

Uh, yeah, only completely.

this might be the only place, where the JLS3 mentions
»constants in classes«.

Section 15.28, "Constant Expression", provides the definitive definition:
<http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.28>
Qualified names of the form TypeName . Identifier that refer to constant variables

In other words, a static final variable that refers to a constant.

It also references section 4.12.4,
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable.

Not only are constants used in classes, but it's a bad idea to define constants in interfaces.

--
Lew
.