What is the difference between constant declaration in interface and in java class

1) What is the difference between two static variables below the code.

Class A{ public static final String X = "XYZ"; } interface A{ String X = "XYZ"; } 

2) if both static are a variable declaration, are the same and which are effective.

t

 Class A{ public static final String X = "XYZ"; void print(){ System.Out.Println(X); } } 

OR

 interface B { String X = "XYZ"; } Class A implements B{ void print(){ System.Out.Println(X); } } 
+4
source share
5 answers

1) Both constants have the same meaning. By default, fields declared in an interface are public static final .

2) Fields in the interface should not be preferred. (until you are sure that the other interface will not have a field with the same name).

 interface A { String X = "XYZ"; } interface B { String X = "ABC"; } class C implements A, B { public static void main(String[] args) { System.out.println(X); // Ambigous X } } 

3) Efficiency does not depend on where you place the constant; in class or in interface.

+1
source
  • There is no difference between the fields. From the section in section 9.3 of the JLS :

    Each field declaration in the body of the interface is implicit public, static, and final. It is allowed to over-specify any or all of these modifiers for such fields.

  • There is no difference in performance, because in both cases the compiler will "embed" the value of the field in any case: at run time it will not access the fields anyway. This is just the case, because you are using String , though; if the field was a type other than a primitive type or String , the code will access the field ... but I would not expect this to ever have a significant impact on performance, and you should not worry about that. Instead, write the cleanest code.

+5
source
  • There is no difference in how the field type was created. Both methods create a constant field.
  • The difference in efficiency is negligible, if any. You should care more about network latency and the like when it comes to efficiency. This will affect your application 10 million times more than that, and it is likely to be conservative. With things, this trivial, readability is much more important than efficiency, so do everything that is clearer.
0
source

Pecularity is that the variables ALL , denfined in the interface, are public final , not to mention this.

0
source
  • There is no difference in performance.
  • It is more a design decision than a performance-oriented one.
  • My choice for declaring constants will be fine:

a. Enum
b. Interface
with. Classes

I remember this issue was briefly discussed in the book "Effective Java."

0
source

All Articles