When java in the modified method static? What are the advantages or disadvantages?

When a method or variable needs to initialize load, or is often invoked when coupled with static. 
A modified static methods can be called directly by the class name, instance of an object must first unused can then invoke 
such a person inside the class method public static add () {} 
that can be called directly with the person class person.add (); course can use the following methods to call an object are possible 
if this method is not static, such as in front of public add () {} 
then the first to person p = new person (); 
then p.add (); 
when the class loader loads the class has been instantiated this class. 
Disadvantages: initialization load, comparison of total memory, it is not often used method is not recommended add this keyword. 

If static is written in a single case, the high concurrent access is likely to go wrong, this time we should set up a thread to wait, when the container is static loading has been loaded into memory, so static methods and variables should not be overused, selective use. 

If you need to calculate by initialize your static variables, you can declare a static block, Static block is executed only once when the class is loaded. The following example shows the class has a static method, a number of static variables, and a static initializer block: 
. // Variables the Demonstrate static, Methods, and Blocks 
class UseStatic {
int. 3 = A static; 
static int B; 
static void Meth (int X) { 
System.out.println ( "X =" X +); 
System.out.println ( "A =" + A); 
the System.out. the println ( "B =" B +); 
} 
static { 
System.out.println ( "Block the static a initialized."); 
B = A *. 4; 
} 
public static void main (String args []) { 
Meth (42 is); 
} 
} 
Once UseStatic class is loaded, all static statement is executed. First, the variable class attribute assignment begins, A is set to 3, b is initialized to 0 by default, then run static block execution (printing a message), and finally, b is initialized to a * 4 or 12. Then calls the main (), main () calls meth (), the value 42 is passed to x. 3 println () statements refer to two static variables a and b, and the local variable x. 
Note: Reference to any instance variables are illegal in a static method. 
Here is the output of the program: 
. A initialized the Static Block 
X = 42 is 
A =. 3 
B = 12 is

Guess you like

Origin blog.csdn.net/weixin_42043101/article/details/87020128