The use of Java in the static

A static member variables

We all know that we can create multiple objects based on a class of this class, each object has its own members, independent of each other. However, at some point, we hope that all members share the same class object. Static at this time is the time to show their talents! !

Java was modified static members are called static members or class members. It belongs to the class of all, not all of an object, ie the class of all objects are shared. Static members can directly access the class name, object name can be used to access it. Of course, given the special nature of his role is more recommended to use the class name to access ~~

You may be modified using the static variables, methods and code blocks.

In this section, we first get to know about static variables.

For example, we define a static class variable Hobby, operation code as follows:

operation result:

Oh, to pay attention to: Static members belong to the entire class, when the system for the first time this class, it will assign the memory space will be uninstalled until the class is recycling! ~~

Second, the static member methods

As with static variables, we can also use static modification method, called static method or class method. In fact, we have been written before the main method is a static method. Use static methods such as:

operation result:

requires attention:

1,  a static method can call the same static members, but can not call non-static member directly. Such as:

If you want to call non-static variable in a static method, you can create a class of objects, then to access the non-static variables through an object. Such as:

2, in the conventional method, a member, can directly access the non-static and static variables are the same, as follows:

3, static methods can not directly call a non-static method, you need to access non-static methods through an object. Such as:

 

Third, the static initialization block

Java can be assigned by the initialization data block. Such as:

In the class declaration, may comprise a plurality of initialization block, when creating the instance of the class, it will execute the code block sequentially. If you are using a modified static initialization block, it is called static initialization block.

Require special attention: the static initialization block is executed only when the class is loaded, and only once, at the same time the static initialization block only to the static variable assignment, can not initialize an ordinary member variables.

Let's look at a piece of code:

operation result:

通过输出结果,我们可以看到,程序运行时静态初始化块最先被执行,然后执行普通初始化块,最后才执行构造方法。由于静态初始化块只在类加载时执行一次,所以当再次创建对象 hello2 时并未执行静态初始化块。

 

Guess you like

Origin www.cnblogs.com/Elliott666/p/11413836.html