Interface Vs Final class to store the final variables - java

I have a class which contains only final variables.
E.g:
public class Constants
{
public static final String PREFIX = "some prefix";
public static final String SUFFIX = "some suffix";
//and so on...
}
Which type is recommended here - an interface or a final class?

Interfaces are used to define a contract. In the code you copy paste, these constants should be defined in a final class. Check What is the best way to implement constants in Java?

You should use a Final Class for this.

If you are creating a class which contains only globaly accessible final constants you should use enum.

Global constants as you put it should actually be in a properties file as it allows each application to configure them individually without a code modification. For object specific constants my general rule of thumb on Enum versus static final I typically lean towards how many elements there are to have and how related those elements are. If there is a big relation between them such as Suits in a deck of Cards then I would go for the enum. If it is default age for a user, then this becomes a final as there is no purpose to making it an enum as it would not need to be referenced in many areas. These are just some thoughts on each of the ways I have approached it.

Related

Separate Interface or Utility class for defining constants in core java project

I am working on a project (using JDK7) which has 30 to 40 constants. These constants are being used by many classes of my project. I want to separate these constants into a single file. Which type of file should I prefer?, Interface or Utility class, I am thinking of using interface. Would it be appropriate ?
According to the SonarQube rules Constants should not be defined in interfaces
You should use a class or an enum.
I use a class with a private constructor in the case.
But be aware you should only put constants together in one file it there is a conceptual connection between them. Do not simply store a bunch of unrelated constants in a class.
If the constants may change over time because they are more of the configuration type, I would go the extra effort to store them in a configuration file.
I do it like this..
class Constants {
private Constants() {
}
public static final String CONST_1 = "";
//add your constants here as public static final properties
}

Use static properties for constants with java

In my java program I use a Constants.java class. In this class I created about 50 Strings properties in this way
public static final String startError = "The program could not be started, please ......";
public static final String logPath="/Users/hgvu/";
In my program I use this class in this way for example
System.out.println(Constants.startError);
I am new in the domain, do you think it's a good idea to make fields in the Constants class static ?
Make your class final, like public final class Constants. And Java doesn't let you create top-level static classes, I think you meant making fields static when you asked "do you think it's a good idea to make the Constants class static". The answer is yes, it is the best way to go about it.
In my opinion Constants should not vary - therefore they should always be static... This also means you can access the constant variable values without having to initiate the Constants.java class
you wont be able to define a Static class in java unless it is nested, but if you want the constants to be shared across, then making it a nested class does not make any buyout.
But you can make your class final and have private constructor would be a good choice if you want this class to only contain your constants

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.
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.
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.
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!

Header like Class for defining constants in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you define a class of constants in Java?
I would like to define a class in my package to contain only the constant vales like defines in C. I am a C programmer learning Java so perhaps that is why I still want to have some header like class :)
For this purpose here is the class I have:
package com.myclasses
public class defines{
public static byte final ID_1= 0x01;
public static final ID_2= 0x02;
public static String company_name="XYZ";
}
Then somewhere in a another class in the same package, I use these defines as follows:
byte idval = defines.ID_1;
... and so on.
My question is for such a "header" class what is the best way of defining it?
It has only static variables so should I define the class also static?
What about the access modifier? Since it has defines in it I thought it could be made "public".
Please advise.
Don't
There are hardly any constants that have value in their own. They only make sense in context. That context is a real class, i.e. a class that has instances (at least one). Declare the constants in that class.
As for the modifiers: reduce the scope as far as possible: Private if only used inside the class where they are declared, public if anybody using the class needs the constants as well.
If you declare more then one constant of same type in one class, think about if a enum makes mores sense.
And yes, constants should be static.
This pattern is called the "constant class" pattern (I think).
One way of using it is to make it an interface and implement it, then you get the references for "free":
public interface Defines {
static byte final ID_1= 0x01;
static final ID_2= 0x02;
// etc
}
public class MyClass implements Defines {
byte idval = ID_1; // Note: No need to refer to the class "Defines" here
}
but most people consider this an anti-pattern, because it isn't a real interface (it has no methods). Nevertheless, it is kind of cool, and may be a good way for you to ease into java.
The "standard" approach is to define a "utility class", which is one that has only static fields and methods, give it a private constructor to reinforce that you shouldn't create one of these. This is what you have done - keep doing it.
If you have a few constants that are different values of "the same thing", eg directions on a compass, etc, strongly consider using an enum. You should read up on them.
Use a final class
eg : public final class defines {
// private constructor
private defines() {
}
}
The constants should be defined as
public static final <type> constantName = <value>;
Wouldn't recommend enums in this scenario as Enums should be used when we are having constants which are having some relation between them.
Having a utility class like this, is the approach we use in our project to define constants that needs to be accessed across a project.
If you needs the constants only in that certain class then defining them in the class itself will be the best solution. eg:
private static final <type> constantName = <value>;
Just use an Interface in Java to define all your Constants..
public interface Const {
String GOVERNMENT = "Government";
String PUBLIC = "Public";
...
}
You can use class also.

How can I have a constant variable common to all classes in a package?

I want a constant variable to be common to all classes in a package. Is there a way I can do this without making an interface just with the one definition in it, and making every class implement that?
In Java, all constants have to reside in a type (class or interface). But you don't have to implement an interface to use a constant declared inside.
You can try by putting something like this in your package:
interface Constants {
static final String CONSTANT = "CONTANT";
}
and then, using it like this:
String myVar = Constants.CONSTANT;
This way, you still have your interface, but no classes implement it.
Generally applications have a "Constants" class or interface that holds all constants.
I generally to to group constants into logical classes. For instance if there can be two kinds of employees, regular and contract:
class EmployeeType
{
public static final String REGULAR = "regular";
public static final String CONTRACT = "contract";
}
and use it as EmployeeType.REGULAR
If the constants cannot be grouped this way, have a separate class/interface to hold these.
class Constants
{
public static final String APPLICATION_DOMAIN = 'domain';
}
You need not extend/implement this class interface to use the values. The constants will generally be declared public static final, you can access them directly: Constants.APPLICATION_DOMAIN
Use a package private class:
class Constants{
public static final int MY_VALUE = 1234;
}
This can only be accessed by classes from the same package:
int val = Constants.MY_VALUE;
You can do this in various ways:
One way (as mentioned here) is to create a Global constant interface and have a public static final attributes of each constants.`
Create properties file. By having a properties file, you'll have a Key value pair (separated by a = operator) each declared on a newline. Here's a tutorial on how to create and use properties file.
Seems like to be a good candidate for an entry in a property file to me.
You can use an abstract class to serve as the base class for each impls in that package.
You could make a special (static) class with just this variable. Later you can add other constants or whatever you need to that class.

Categories