Java Basics 5: static keyword

First, the concept

The static keyword to create an object is modified not need to call directly from the class name can go visit. Facilitate calls without creating an object down.

It may be modified internal static classes, methods, code block variable.

Second, the use of

2.1 Modified internal class

static inner classes can only be modified, the general category is not allowed to be declared as static. The famous singleton pattern is static inner classes.

public class Singleton  {    
    private Singleton() {}
     
    private static class SingletonHolder {    
        public static final Singleton instance = new Singleton();
    }    
 
    public static Singleton getInstance() {    
        return SingletonHolder.instance;    
    }    
}

2.2 modification methods

A method of modifying the time, in fact, with the same class can be invoked directly by the class name.

public static void main(String[] args)//main方法是所以方法的入口

2.3 Modified block

public class Father {
    private static int i = 1;
    private int j = 1;

    static {
        System.out.println("父类静态代码块,i:" + i);
    }

    {
        System.out.println("父类普通代码块,j:" + j);
    }

    public Father() {
        System.out.println("父类构造器");
    }
}

public class Son extends Father {
    private static int i = 2;
    private int j = 2;

    static {
        System.out.println("子类静态代码块,静态属性 i:" + i);
    }

    {
        System.out.println("子类普通代码块,普通属性 j:" + j);
    }

    public Son() {
        System.out.println("子类构造器");
    }

    public static void main(String[] args) {
        new Son();
    }
}

output:
父类静态代码块,静态属性 i:1
子类静态代码块,静态属性 i:2
父类普通代码块,普通属性 j:1
父类构造器
子类普通代码块,普通属性 j:2
子类构造器

Variable has been assigned is output from the point of view, be described block member variable is initialized priority.

Class initialization sequence:

Parent class static variables, static block of code ->
subclass static variables, static block of code ->
parent class ordinary variables, common block constructor ->
subclasses normal variables, common block constructor

2.4 Properties modification

Modified static member variables is called a static variable, also known as class variables, indicating that this variable belongs to this class, and not to the object.

public class Car {
    private String name;
    private String engine;
     
    public static int numberOfCars;
     
    public Car(String name, String engine) {
        this.name = name;
        this.engine = engine;
        numberOfCars++;
    }
 
    // getters and setters
}


@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
    new Car("Jaguar", "V8");
    new Car("Bugatti", "W16");
  
    assertEquals(2, Car.numberOfCars);
}

static method variables can not be modified, otherwise it is not a class level. Principle needs to be analyzed from the Java memory model.

Third, in-depth analysis of the static keyword

First look simple Java memory zoning
Here Insert Picture Description

3.1 PC register (program counter)

Thread private. Save the current thread bytecode executed by the line number indicator, execution environmental context. java multithreaded execution time is, by way of rotation of the thread switching processor and assigned to implement, so each thread in order to after the handover to resume the correct execution position, each thread will have a separate program counter, each independently of each other between the threads, isolated storage.

3.2 JAVA virtual machine stack (Java method stacks)

Thread private. Creates a stack frame when performing each method, the local variable table for storing information, the operand stack, dynamic link, the method exports. Each method execution until completion of the procedure is called, a corresponding stack frame of a process to push the stack in a virtual machine. Local variable table includes local variable data type basic compiler knowable, and returnAddress object reference type (address points to a byte code instruction).

3.3 native method stacks

Thread private. Native execution method.

3.4 Java heap

Threads share. Storage object instance. java heap is the main area managed by the garbage collector, and therefore often also referred to as GC heap. java heap can also be broken down into: the old and the new generation's; and then there is little detailed Eden space, From Survivor space, To Survivor space.

3.5 Method area (static area)

Threads share. Storage class binary file that contains information about the type of virtual machine load, constant, static variables, the time compiler to compile the code and other data.

Constant pool area is part of the method, the main storage of two categories constants: literal (the Literal) and reference symbols (Symbolic References). Literal constants concept closer to the Java language level: Declared as a constant final basic types of constant pool, a string constant pool. The concept of symbolic references principle aspects of the compilation belongs.

jdk1.6 string constant pool area in the process, after 1.7 in the stack. Runtime constant pool in the area has been the method.

Start jdk1.8, remove the permanent generation of concepts, methods district implemented dimensional space.

3.6 heap, stack difference area for storing data and methods

Stack: variables declared in the method, the method is invoked whenever the program, the system will establish a method for the method stacks, variables declared in the method in which it is placed on the stack method, the method ends when the stack will release method, which the corresponding variables declared in the process ended with the destruction of the stack. Storing a local variable values ​​(basic data types), the local variable references.

Heap: storage of object reference types, non-static member variables value (basic data types) class, non-static member variable references.

The method area: storage class binary file that contains class information, basic information about the static member variables, constants pool (String string and final modification of constant values, etc.), like the version number. Static member variables are static field method inside the area, while static member method is a method in the class of binary information area inside.

This is the local variables can not be modified static reasons: Any thread calls the method each time, will open up new space in the stack. Different threads executing the same method, the method and independently of each other between the method parameter value passed in the same method are not different in the stack, local variables and assignment initialization NATURAL performed on the stack, it can not be static keyword with modification of local variables.

Reference links:
https://baijiahao.baidu.com/s?id=1636927461989417537&wfr=spider&for=pc
https://blog.csdn.net/qq_36470686/article/details/82957221
https://www.baeldung.com/java -static


Micro-channel public number: Thinking in program
Jane book: https: //www.jianshu.com/u/0a500b9f1fe1
CSDN:https://blog.csdn.net/guo_dong_dong
If you have any suggestions and comments on the article, welcomed the attention of the public contact number

Thinking in program

Published 10 original articles · won praise 1 · views 470

Guess you like

Origin blog.csdn.net/guo_dong_dong/article/details/104036702