Advertisement
ElectronGuigui

Constants in java

Jul 2nd, 2015
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. //The class defining constants:
  2. package com.mypackage;//the class "Constants" is in the package "com.mypackage"
  3. public final class Constants {
  4.     public static final int CONSTANT_A = 25;
  5.     public static final String CONSTANT_B = "This is a public static final String";
  6. }
  7.  
  8.  
  9. //Another class that use these constants (in a separate file in the same package):
  10. package com.mypackage;//the class "MyClass" is in the package "com.mypackage"
  11. import Constants.CONSTANT_A;//we import the value "Constants.CONSTANT_A" to use it more easily
  12. public class MyClass {
  13.     public void exampleofConstantsUse() {
  14.       System.out.println(Constants.CONSTANT_B);//need to specify the constants class name because there is no import
  15.       System.out.println(CONSTANT_A);//don't need to specify the constants class name because of the static import
  16.     }
  17. }
  18.  
  19. //Another class that use these constants (in a separate file in a DIFFERENT package):
  20. package com.package2;//This class is in another package
  21. //Instead of writing "import com.mypackage.Constants.CONSTANT_A;" for each constant value, write:
  22. import com.mypackage.Constants.*;
  23. public class MyClass {
  24.     public void example() {
  25.         System.out.println(CONSTANT_A);//prints 25
  26.         System.out.println(CONSTANT_B);//prints "This is a public static final String" (without the quotes)
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement