Introduction to static in Java

Source: Internet
Author: User

Static modified member variables: static modified member variables are also called class variables or global variables. When a class is loaded, the static modified member variables are initialized and associated with the class. As long as the class exists, static variables exist.

A static variable is used to separate a bucket and is not bound to a specific object.
Shared by all objects of the class. That is to say, when an object is declared, it does not produce a copy of the static variable, but all instance objects of this class share the same static variable. Static
Modified member variables can be accessed before any instance object is created without referencing any object. That is to say, no matter how many objects are created, the static modified variables only occupy one piece of memory.

Static: For class attributes
YesClass variables and instance variables

Class statictest
{Static int I = 47;
}
For different objects, statictest ST1 = new statictest (); statictest st2 = new statictest () both
There is only one shared bucket!

There are two methods to reference static variables. You can use an object to locate them .. You can also use its class name to call it directly!(It is best to pass the class name so that the program reader will not be confused)

If a member is declared
Static
He justIt can be accessed before its class object is created,
You do not need to reference any object.The most common example is

Main ()
Method,
Static
The Defined variables take precedence over any other non-
Static


Variable, regardless of the order in which it appears;

Java variables are divided into two types at the class level,Static and instance variables,
However, you cannot directly access instance variables in static methods. You need to initialize an instance of the class to use instance variables.


The reason why static things are differentiated isTreat members of classes and objects.
If a variable or method is declared as static, it meansMemory space must be allocated during class initialization.
Method callSince the internal variable is temporary, it will become invalid as the method call ends.
So there is no reason to make it static, right?

1Static variables belong to the class and are shared by all objects of the class. The memory space is allocated before the program starts execution,
This function can be similar to the global variables in VB.
If final is added, the function is similar to a global constant and its value cannot be modified. For example, the circumference Rate


2Static Method of. Class
Instance variables of the category class are not supported,
Static variables that can be renewed and instance variables of instantiated classes


3
. Static methods cannot define static variables


Like the author, I recommend the following code:

Public class explicitstatic {
Public static void main (string [] ARGs ){
System. Out. println ("Inside main ()");
Cups. c1.f (99 );
}
Static cups x = new cups ();
Static cups y = new cups ();
}
Class cup {
Cup (INT marker ){
System. Out. println ("cup (" + marker + ")");
}
Void F (INT marker ){
System. Out. println ("F (" + marker + ")");
}
}
Class cups {
Static cup C1 = new cup (11 );
Static cup C2;
Cup C3 = new cup (33 );
Cup C4;
{C3 = new cup (3 );
C4 = new cup (4 );
}
Static {
C1 = new cup (1 );
C2 = new cup (2 );
}
Cups (){
System. Out. println ("Cups ()");
}
}


/* Output result:
Cup (11)
Cup (1)
Cup (2)
Cup (33)
Cup (3)
Cup (4)
Cups ()
Cup (33)
Cup (3)
Cup (4)
Cup ()
Inside main ()
F (99)
*/
/*

The first Initialization is static, and the order is the code order up-to-down! Then the method is called by yourself!

The preceding execution sequence is
1: static cups x = new cups (); transferred to cups object
2: static cup C1 = new cup (11); transfer to cup object
3: CPU output (11 );
4: static cup C2 in the cups object;
5: static {
C1 = new cup (1); transfer to cup object output cup (1)
C2 = new cup (2); transfer to cup object output cup (2)
}
6: cup C3 = new cup (33) In the cups object; Output cup (33)
7: C3 = new cup (3); Output cup (3)
C4 = new cup (4); Output cup (4)
8: CUPS (){
System. Out. println ("Cups ()"); Output cups ()
}
9: static cups y = new cups ();

Note that the static members in cups have been initialized, so static cup C1 = new cup (11 );

Static cup C2; static {
C1 = new cup (1 );
C2 = new cup (2 );
}
Not executed!
The following is the same as above!
*/


The first time static initialization occurs. During loading, all static objects and static code blocks are initialized in the original order (that is, the order in which they are written in the class definition code ).
Of course, static data is initialized only once.


The program first accesses the main method, and then starts to load the corresponding class file. If the program has a base class, it loads the base class, and finally completes static initialization.

Certificate -----------------------------------------------------------------------------------------------------------------------------------

《

Suggestion: use static variables with caution.

"

(Transferred from Forum)
In the past two days, we held a training course on the human resources system and found a problem: the session value is messy. At first, we thought it was a session problem, but through tracking, the data value is completely correct without any exceptions. Finally, the session is found to change through the alternate execution of the job,It is found that a value is static before being passed in;
So,For static variables, after a writes the session, the job has not been continued, B re-writes the session and the job is completed, and then a continues the job, the session value obtained by a is no longer the original value.

(Reply)
Static is actually an address, so there will be such a problem.

If needed, you can use Singleton mode (Singleton mode ).

In Java, you must use static variables with caution.

The scope of the variable is not clearly defined, and problems will certainly occur. After analyzing your own purposes, it is very effective to use static. For example, you can find the company address book (because it remains unchanged) in the servlet and save it to the static variable so that it only interacts with the DB once :).

If it is not a public variable, do not use static.

Certificate -----------------------------------------------------------------------------------------------------------------------------------

Static Block

Var1 and var2 are defined as final, and the value exists in a properties file. Before using var1, you must load the value in:

System. getproperties (). Load (New fileinputstream ("constants. properties "));

Put the code in the static block:

Punlic final class constants {

Static {

System. getproperties (). Load (New fileinputstream ("constants. properties "));

}

 

Public static final int var2 = system. getproperties (). getproperty ("var2 ");

Public static final int var1 = system. getproperties (). getproperty ("var1 ");

}

However, var1 and var2 are not assigned values during runtime. After debugging, it is found that the static block is not executed at all.
So epiphany:Final variables are computed and assigned values during compilation. Therefore, static blocks are not required during runtime.

Certificate -----------------------------------------------------------------------------------------------------------------------------------

 

Java can use the static keyword to modify the member variables and member methods of the class. Static modified member variables. Member methods are generally called static (or global) variables (static field) and static methods ).

Different from common variables and methods, static variables and static methods are all objects of the class. That is to say, during runtime, all objects of the class access the same static variable value in the program space. When one of the objects changes the value of the static variable, other objects will be affected.

Because of this, static variables and static methods can (recommended) PassClass Name. static variable/class name. Static Method
Direct access.

Object. Variable/method:

Without static modification, the member method acts on the object domain, which is usually called an object variable (Instance
Field), object method (Instance
Method ). When an object is created, it actually exists in the memory space, and the change of the object itself does not affect other objects. It's like
The change of zhangsan, an object of person, does not affect other person objects.

Class. Variables/methods:

Member variables modified using static,Member methods can be seen as inherent in a class. They act on all objects of the class.
When all objects of a class need to share the same value, you can use static to define it.

For example, if a store (class) has multiple stores (objects), you can use a static variable to describe the total turnover of all stores, in this way, each branch can simply access (read/write) the total turnover of the Public store.

Another example is Pi = 3.1415926. In this case, you can use static to define the PI variable. Of course, static final is usually used to modify static variables.

Certificate -----------------------------------------------------------------------------------------------------------------------------------

1. If you need to initialize your static variable through calculation, you can declare a static block, which is only executed once when the class is loaded.

2,
The variable declared as static is essentiallyIs a global variable.
When declaring an object,Instead of generating a copy of static variables, all instance variables of the class share the same static variable.
Methods declared as static have the following restrictions:

◆ They can only call other static methods.
◆ They can only access static data.
◆ They cannot reference this or super in any way

3. variables declared as static are initialized at the defined place and can only be initialized once.

That is to say, if you define a static variable in a method, the variable will not be initialized again when you call the method for the second time.

4,If it is declared as static, only one portion of memory space will be occupied and will not change.
.
It is initialized only once when the class is loaded.
.
It can be called by the class to which it belongs...


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.