Learning Java: static keyword overview


Overview of the static keyword

Once with the static keyword, then such content is no longer belongs to the object itself. But it belongs to the class, so all of this class of objects, both share the same one.

If there is no static keyword, you must first create an object before you can use it through an object.

 

Whether it is a member variable or member method. If you have a static, we recommend the use of class names called.

Static variables: Static variables class name. 
Static methods: the static method the class name (). 
Int NUM; // member variable 
static  int numstatic; // static variables 

public  void Cainiao () {} // member methods 
public  static  void CaiNiaoStatic () {} // static method
 // can not access the member variables
 // static methods can not access this keyword

Precautions:

1. Static methods can not directly access non-static variables.

  • The reason: because the memory of them is [to] have static content, [after] some non-static content.
  • "Ancestors knew descendants, but descendants do not know their ancestors."

2. static methods which can not use this.

  • The reason: this represents the current object, by means of who called, who is the current object.

Note:
According to the time the class name to access static member variables and objects on the whole matter, and just like a relationship.

 

Code block is a static format:

public  class class name {
     static {
         // content of the static code block 
    } 
}

Features: When used in this first class, the only time a static block of code.
Static content always take precedence over non-static, static code before execution so than the constructor.

Typical uses static code:
for once static member variables assignment.

 

Guess you like

Origin www.cnblogs.com/cainiao-chuanqi/p/11106671.html