Introduction to defining constant methods in Java

  • 2020-04-01 02:24:22
  • OfStack

Java is no The global variable Is it still called OO with global variables? ; Reason: Java makes all design object-based. Java global variables can only be used within a class. Variables that can be used anywhere in a class are global variables, while variables that are used only within a particular function or local block are local variables.

So: A variable declared static is essentially a global variable. When you declare an object, instead of making a copy of the static variable, all the instance variables of the class share the same static variable.

Use: There are only static and non-static variables in Java, which belong to each class, if you need global variables such as PI(3.14...). , we can write a class Math, define the static variable PI, call math.pi can be used, so that we can use the global variable.

1. Declare the required constants in a package into an interface such as XyzConstants,
Just declare it like a normal field.


public interface SomeConstants {
   public intPORT = 80;
   public String IP = "166.111.16.1";
   public boolean test = true;
} 

You can.
Implements, the interface for a class that USES a constant. In the simple case, just have fun.

2. A more formal approach is to write a class that maintains all the constants and is responsible for reading the values of all the constants from a configuration file, such as a properties file or an XML file.
You can initialize all static variables from a configuration file in a static {} block. This improves the configurability of the software. Change some east east need not move code, better.
It is best to have a config Tool for writing configuration files.

3. Other instructions:

Define a public class with a static variable in it.


public class infos{
  private infos(){
  }
   public static int PORT = 80;
   public static String IP = "166.111.166.111";
   public static boolean test = true;
   public static final String MYNAME="zzz"; //If I use final in my definition, I can't change it.
}

In other class call these variables are: infos. PORT, infos. IP, infos. Test, infos. MYNAME
When multiple classes interact, information can be passed by changing the values of these variables. For example, if infos.test is changed to false by another class, it may indicate that something has failed or has been done, and the other class can know this information in advance.

Where infos.myname is defined as final, that is, as a constant. A member variable with final modifiers represents a constant whose value cannot be changed once given!


Related articles: