Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //The class defining constants:
- package com.mypackage;//the class "Constants" is in the package "com.mypackage"
- public final class Constants {
- public static final int CONSTANT_A = 25;
- public static final String CONSTANT_B = "This is a public static final String";
- }
- //Another class that use these constants (in a separate file in the same package):
- package com.mypackage;//the class "MyClass" is in the package "com.mypackage"
- import Constants.CONSTANT_A;//we import the value "Constants.CONSTANT_A" to use it more easily
- public class MyClass {
- public void exampleofConstantsUse() {
- System.out.println(Constants.CONSTANT_B);//need to specify the constants class name because there is no import
- System.out.println(CONSTANT_A);//don't need to specify the constants class name because of the static import
- }
- }
- //Another class that use these constants (in a separate file in a DIFFERENT package):
- package com.package2;//This class is in another package
- //Instead of writing "import com.mypackage.Constants.CONSTANT_A;" for each constant value, write:
- import com.mypackage.Constants.*;
- public class MyClass {
- public void example() {
- System.out.println(CONSTANT_A);//prints 25
- System.out.println(CONSTANT_B);//prints "This is a public static final String" (without the quotes)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement