Is there any advantage of NOT having a class implement
an interface and instead use the final fields directly? For example:
p开发者_如何学JAVAublic interface MyInterface {
int CONST_A = 16;
int CONST_B = 45;
}
Approach 1:
public class MyClass implements MyInterface {
MyClass() {
System.out.println("A = " + CONST_A);
System.out.println("B = " + CONST_B);
}
}
Approach 2:
public class MyClass {
MyClass() {
System.out.println("A = " + MyInterface.CONST_A);
System.out.println("B = " + MyInterface.CONST_B);
}
}
I was wondering if any of the approaches above has advantage of any kind over the other. One of the places this situation occurs is in Blackberry where you have your localized texts defined as an interface with keys to the strings and you need to call a system API with the key as the argument in various parts of the code.
It is considered a bad practice to put constants in interfaces and to implements those interfaces to access the constants. The reason is, many classes could implement the interface, thus providing many access points to the same constants.
So, to answer your question, I'd rather use the second solution. Even better, I'd put the constants in a final class, so that there is only a single point of access to the constants. It'd be clearer, and would be easier to refactor.
use enumeration for constants (Effective Java)
For example define like that and call KernelError.KE_UNDEFINED_CALLER
public enum KernelError {
KE_NO_ERROR(0), KE_UNDEFINED_SESSION(1), KE_UNDEFINED_CALLER(2), KE_SESSION_EXPIRED(
3), KE_NULL_VALUE_IN_SESSION(4), KE_N0_SUCH_METHOD(5);
private KernelError(int errorCode) {
setErrorCode(errorCode);
}
private int errorCode;
/**
* @return the errorCode
*/
public int getErrorCode() {
return errorCode;
}
/**
* @param errorCode
* the errorCode to set
*/
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
If you defined constants in interfaces and, for example, define MyInterface2
which has a constant CONST_A
, they conflict. Personally I think that approach 2 is easier to read.
I prefer approach 2 as it does not pollute the namespace of the using class with all possible constants. This reduces the number of code completion choices. Also, when looking at a use of a constant, the qualified name makes it obvious that it is a constant, and where that constant is defined.
That is, I prefer
interface Constants {
static int A;
static int B;
}
void foo() {
System.out.println(Constants.A);
}
to
interface Constants {
static int Const_A;
static int Const_B;
}
void foo() {
System.out.println(Const_A);
}
精彩评论