Java basics: a comprehensive understanding of the static keyword static

I. Definition:

A representation of static properties keyword / modifiers

ROLE

1. Role: common, shared

Meaning is to be modified static content that can be shared by all objects directly say "common, shared," We may be more abstract to illustrate by example..:

For example,
Name: Joe Smith Nationality: Chinese
Name: John Doe Nationality: Chinese

Nationality can be modified using the static

2. reasons

Can have this effect causes Analysis:

  • Java, any variable / time code memory, are automatically assigned by the system memory at compile time;
  • After compiling static variables, the allocated memory will always exist until the program exits will release this memory space;
  • When the class is loaded, the JVM will static variable into the method area is shared by all instances of this class of this class is &;

III. Use

static static modifier may be applied: Class, code block, the method variable &

1. static class

  • Use the static keyword modification, defined as static inner classes

Namely:
static class also known as: static inner classes
of such independent existence, form and external relations inside and outside class, in fact it is not, essentially in order to hide itself

  • Specific rules related to the use of &
/**
 * 1. 静态类的方法 = 静态 / 非静态
 *    (静态方法可在外层通过静态类调用,而非静态方法必须要创建类的对象后才能调用)
 * 2. 只能引用外部类的静态变量(static,即类变量)
 * 3. 注:
 *       a. 默认不持有外部类引用、使用不依赖于外部类(与外层类无绑定):即使无创建外层类的对象,它一样存在
 *       b. 若一个内部类不是被定义成静态内部类,那么其成员变量 / 方法不能被定义成静态
 *       c. 静态内部类 & 非静态内部类在创建时有区别,下面会详细说明
 */

// 外部类
public class A {  
    // 静态内部类
    public static class B{  
    }  
    // 非静态内部类(即 普通)
    class C{  
    }  
}  

// 静态内部类b & 非静态内部类c   创建时的区别:
A a=new A(); 
A.B b=new A.B(); 
A.C c=a.new C();
  • The difference between static inner classes and inner classes

Here Insert Picture Description
(Click to enlarge the view)

  • Special attention
    a. Loading a class, the class would not inside thereof while being loaded.
    . b time for a class is loaded: When and only when it is called a static member (static field, structure, static methods)

2. static code block

  • Definition:
    the final step 1 (class initialization) class loader to load the class, a set of statements executed class constructor () need be performed in

Additional instructions

① class initialization = really started class defines Java code = execution class constructor ()
② () = automatically by the compiler to collect class assignment operation for all the class variable & static statements statement in the block merger of
③ with the class constructor (ie instance constructor ()) is different () without explicitly call the parent class constructor, before () the opportunity to ensure the implementation of a virtual sub-class, parent class () has already been performed

  • Features:
    static block of code in the class independent static class member statement block, there may be a plurality, the location can be easily put , it is not any in vivo method, the JVM loads class performs these static code block , if the static code is block has a plurality, the JVM to execute them sequentially in the order they appear in the class, each code block is executed only once . Inside static methods can only be called directly in other similar static member (including variables and methods), but can not directly access non-static class members. Because for non-static methods and variables, we need to create an instance of the class before use, and static methods do not create any objects before use.
  • Specific rules related to the use of &
/**
 * 1. 代码块 使用 Static修饰
 * 2. 静态块只会在类加载到内存中时执行1次
 *    a. 若有多个static代码块,JVM将按照它们在类中出现的先后顺序依次执行
 *    b. 静态语句块中只能访问定义在静态语句块之前的变量,定义在它之后的变量可以赋值,但不能访问。如下实例所示
 */

 public class Test { 

     // 使用静态修饰的静态代码块
     static{ 
         i=0;  // 給变量赋值,可通过编译. 如果这里改成 int i=0; 下一行代码也是可以通过编译的
         System.out.print(i); // 非法, 提示:“非法向前引用” 
     } 

     static int i=1; 
  
 }
  • Non-static block
    static code block corresponding to block a non-static concept.

Non-static block execution order is performed before constructing method, class will be executed once every new.

Disclaimer way: without any modifiers

 {
          //do something
 }

3. static method

  • Definition: Use the static keyword modification, defined as static member method (also called class methods)
  • Specific rules related to the use of &
/**
 * 1. 可直接通过类名调用,也可通过对象实例调用
 *    (属于类,不属于实例)
 * 2. 任何的实例都可调用(方便共享、公用)
 * 3. 只能访问所属类的静态成员变量 & 方法、不能使用this、super关键字
 *   (this = 调用该函数的对象、但由于静态方法可以直接使用类名调用(即可能还没创建对象),所以不可使用this)
 */

// 静态方法的申明
public static void a(int param) {

}

4. Static variables

  • Definition: Use the static keyword modification, defined as static member variables (also known as class variables, global variables)

  • Features:
    the modified static member variables and member methods independent of any object of that class. That is, it does not depend on the class specific example, all instances of the class share. As long as the class is loaded, Java virtual machine will be able to find them in accordance with the method area class name at runtime data area. Therefore, static objects before it can access any object creation, without reference to any object.

  • Specific rules related to the use of &

/**
 * 1. 静态变量在内存中只有1个拷贝:JVM只为静态分配1次内存
 *   a. 全部对象共用这个static关键字修饰的成员变量,方便对象间共享,节省内存
 *   b. 未被static 修饰的成员变量 = 实例变量:每创建1个实例,JVM就会为实例变量分配1次内存,实例变量在内存中可以有多个拷贝(但互相不影响,更加灵活)
 * 2. 可用类名直接访问:在加载类的过程中完成静态变量的内存分配,(也可通过对象实例访问)
 *  (属于类,不属于实例)
 * 3. 非线程安全:因静态变量被类的所有实例共用
 * 4. 局部变量也能被声明为static
 */

// 静态方法的申明
public class A {  

    private static int count = 0;  //静态变量的申明
   
}  
  • The difference between static variables and instance variables
    Here Insert Picture Description(You can click on ways to view)

Four Additional information:

1. In many cases, the use of static, because they can not variable name. Call, only the class name. Calls, such singleton design pattern)

2. When members are static modification, the more an invocation. In addition to the object can be called, it can also be called directly by the class name. Format: name of the class static member

3. Static modified content, in the method area (some books are translated into the shared area, the data area), not in the heap memory

4.static features:

  • With loads and loads of class
  • Takes precedence over the object exists
  • They are shared by all objects
  • Can directly use the class name. Call

5. Static pros and cons:

Advantages:
Shared data object is stored in a separate space, space-saving is not necessary to store each object are a class name may be directly invoked...

Cons:
Life cycle is too long
to access limitations exist only static access static.

? 6. When will define a static method
A: When the internal functions do not have access to non-static data (specific data objects), then the function can be defined as static.

class Person
{
	String name;//成员变量,实例变量。
	
	public void show()
	{
		System.out.println("::::");
	}
	
}

class  StaticDemo
{
	public static void main(String[] args) 
	{
		Person p = new Person();
		p.show();
		
		Person.show();
	}
}

For example, the above Person of the show () method, do not have access to non-static data.
This can be directly written Person.show ();

But if the show () method to change:

public static void show()
	{
		System.out.println(name+"::::");
	}

show () method to access the non-static field name, it is proposed that direct written:

        Person p = new Person();
		p.show();

V. For example tamp

Here is an example often prone in the written part of the interview, we can examine the understanding of static through the entire example, we can deepen the understanding:

package staticblock;
 
public class Parent
{
	//静态代码块,只在类装载的时候执行
	static
	{
		System.out.println("parent static block");
	}
	
	//非静态代码块,每new一次都会执行
	{
		System.out.println("parent non-static block");
	}
	
	public  Parent()
	{
		System.out.println("parent constractor block");
	}
}
package staticblock;
 
public class Child extends Parent
{
	//子类静态代码块
	static
	{
		System.out.println("child static block");
	}
	
	//子类非静态代码块
	{
		System.out.println("child non-static block");
	}
	
	//子类构造方法
	public Child()
	{
		System.out.println("child constractor block");
	}
	
	//静态方法需要在调用 的时候才执行
	public  static void get()
	{
		System.out.println("this is a static method!");
	}
	
	public static void main(String[] args)
	{
		new Child();
		System.out.println("------------------");
		new Child();
		Child.get();
	}
}

After performing printing results are as follows:

parent static block
child static block
parent non-static block
parent constractor block
child non-static block
child constractor block
------------------
parent non-static block
parent constractor block
child non-static block
child constractor block
this is a static method!

Description:

We see that in the implementation of the static code block is executed only once, rather than static code block is executed twice, need to call the static method will be performed. The order of execution is to perform a static block parent class, then perform a static block subclass; then execute non-static block parent class, then the constructor is executed parent class; after again performing non-static block subclass, the constructor is executed again subclass. Execution sequence: static block of code> block non-static> constructor.

Six .Android of caution static

In the aforementioned shortcomings of the static life cycle is too long, the following were talking about on this issue.

1. Use static static static variable potential problems:

(1) occupies the memory, and the memory is generally not released;

(2) automatically reclaims memory in the system is not static memory situation, this will lead to access global static error.

(3) can not be static activity as a static object, so that all components activity objects are stored in global memory, and will not be recovered;

2. Static variable life cycle:

(1) class is loaded at what time?

When we start an app when the system creates a process, this process will load an instance of the Dalvik VM, and then run the code on the DVM, like loading and unloading, garbage collection and other things by DVM responsible. That is when the process starts, the class is loaded, the static variable is allocated memory.

(2) static variable destroyed when the class is unloaded.

Class is unloaded at what time?

At the end of the process.

Description: Under normal circumstances, all classes are the default ClassLoader loaded, as long as there is ClassLoader class will not be unloaded, and the default ClassLoader is consistent with the life cycle of the process, this article discusses the general case.

When (3) the end of the process in Android

This is a process and memory management for Android differs from the core PC - if resources are sufficient, Android will not kill any process, meaning that another process may be killed at any time. The Android will be enough resources in time to restart the process of being killed. That is the value of a static variable, if not treated, is not reliable, it can be said that everything in memory is not reliable. If you want a reliable, Nand still have to save to SD card or go back in time to restart the recovery.

In other cases, you can not quit all Activity equivalent to quit the process, so when the user clicks on the icon to launch the application, the previous value stored in a static variable, it is possible there, so depending on the specific circumstances give emptying operation.

(4) Application is the same unreliable

Application is actually a singleton object, but also in memory, the process is killed when it will be all cleared, but the Android system will help rebuild Application, and our data stored in the Application naturally gone, still have their own deal with.

(5) the object static references will not be garbage

As long as static variables are not destroyed nor set null, which has been the object keeps a reference, that reference count can not be zero, it will not be garbage collected. Thus, singleton object is not recovered during operation.

Further reading: Android programming, which disadvantages of using static variables? How should regulate the use?

Published 81 original articles · won praise 37 · views 50000 +

Guess you like

Origin blog.csdn.net/gaolh89/article/details/94591546
Recommended