What is the best practice to declare a java file having only constant?
public interface DeclareConstants { String constant = "Test"; }
OR
public abstract class DeclareConstants { public static final String constant = "Test"; }
Syntax to assign a constant value in java:static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded. The final modifier makes the variable unchangeable.
Real constants consist of a sequence of digits with fractional parts or decimal points. These constants are also called floating-point constants. The valid examples of real constants are 2.3, 0.0034, -0.75, 56.7, etc. These numbers are shown in the decimal point notation.
With final we can make the variable constant. Hence the best practice to define a constant variable is the following: private static final String YOUR_CONSTANT = "Some Value"; The access modifier can be private/public depending on the business logic.
Neither one. Use final class for Constants
declare them as public static final
and static import all constants wherever necessary.
public final class Constants { private Constants() { // restrict instantiation } public static final double PI = 3.14159; public static final double PLANCK_CONSTANT = 6.62606896e-34; }
Usage :
import static Constants.PLANCK_CONSTANT; import static Constants.PI;//import static Constants.*; public class Calculations { public double getReducedPlanckConstant() { return PLANCK_CONSTANT / (2 * PI); } }
See wiki link : http://en.wikipedia.org/wiki/Constant_interface
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With