0

In java I have seen different approaches to declare the constants. Using interface and class

Assume that some of my class need to use a constant which is hardcoded and can be accessed Constants.MY_CONSTANT_1

Can any one share the memory usage difference of Constant declaration using class and an interface.

Using java interface

public interface Constants{
    int MY_CONSTANT_1=100;
    int MY_CONSTANT_2=200;
}

Using Java Class

 public class Constants{
         public static final int MY_CONSTANT_1=100;
         public static final int MY_CONSTANT_2=200;
}

Kindly summarize :

  1. What is the best approach
  2. Is there any other better approaches
Muhamed Riyas M
  • 5,055
  • 3
  • 30
  • 31
  • 1
    Not really a duplicate of that question. @OP There is no difference in memory usage. – user207421 Mar 05 '19 at 11:03
  • 2
    There's no difference. Fields in an interface are *implicitly* static and final. Your `Constants` class should be declared final and have a private constructor to prevent people from instantiating it, though. Some people use interfaces because it avoids the boilerplate of doing that, but the bad thing about that is that classes could choose to implement it even though it's not supposed to define any behaviour. – Michael Mar 05 '19 at 11:05
  • Have a look to: https://stackoverflow.com/questions/29382728/constant-interface-anti-pattern-clarification – Sodala Mar 05 '19 at 11:06
  • 1
    @Michael No, again, this is not a duplicate of that question. That one is about style. This one is about memory usage. Please read the question, and don't jump to conclusions. – user207421 Mar 05 '19 at 11:28
  • @user207421 The premise that the static field of an interface and the static field of a class would somehow consume different amounts of memory is groundless. Nevertheless, I've added a second duplicate target if someone wanted to calculate that for themselves. Anyway, he asked "what is the best approach" and the best approach encompasses everything, including style. – Michael Mar 05 '19 at 11:31
  • Both outsourcing of shared constants have a code smell, are suspect. Here they seem to lead to range comparisons, ifs. Better - when suitable - would be declarative style, XML or such. An interface is easier, however may lead to `implements Constants`. **Enums** is an alternative for _closed_ value domains. – Joop Eggen Mar 05 '19 at 11:40
  • @Michael Of course it's groundless. That had already been stated twice. That doesn't make this a duplicate of a style question. What he asked is to be found I n the body of the question, not just in the title. You can't just close based on the title. For one thing you don't know what he means by 'best'. You need to read the question. I don't think much of your second link either as a duplicate of this. – user207421 Mar 06 '19 at 03:10

0 Answers0