Java keyword: static


The blogger will use CSDN to record the experience and knowledge gained and learned on the way of software development and study. Interested partners can pay attention to the blogger!
Maybe a person walking alone can walk very fast, but a group of people walking together can go further! Let's learn from each other on the road of growth. Welcome to pay attention!

Use of "static" keyword

1. Introduction

When we write a class, we are actually describing the properties and behavior of its object without producing a substantive object. Only through the new keyword can we produce an object. At this time, the system will allocate memory space to the object and its methods can be called externally. We sometimes hope that no matter whether objects are generated or how many objects are generated, there is only one copy of some specific data in the memory space.
For example, all Chinese have a country name, and each Chinese shares the country name. There is no need to assign a variable to represent the country name in each Chinese instance object.

2. Understanding

Static: static

3. Use

3.1 scope of use

In Java classes, static can be used to modify attributes, methods, code blocks and internal classes

3.2 static modifier attribute

3.2.1 design idea

Class properties are variables shared among objects of this class. When designing a class, analyze which attributes do not change due to different objects, and set these attributes as class attributes. Set the corresponding method to class method.

3.2.2 classification

Property, which can be divided into:
Static attribute (static variable or class variable) vs non static attribute (instance variable)

⭕ Instance variable: we have created multiple objects of the class, and each object independently has a set of non static attributes in the class. When modifying a non static attribute in one object, it will not result in the modification of the same attribute value in other objects.

⭕ Static variable: we created multiple objects of the class, and multiple objects share the same static variable. When a static variable is modified through an object, it will cause other objects to call the static variable. It is modified.

3.2.3 notes

⭕ Static variables are loaded as the class is loaded. It can be called through "class. Static variable".

⭕ Static variables are loaded before objects are created.

⭕ Decorated member, shared by all objects.

⭕ When the access permission allows, you can directly be called by the class without creating an object.

⭕ Since the class will only be loaded once, the static variable will only exist in memory: in the static field of the method area.

⭕ No matter how many objects are created, static data only occupies one storage area.

⭕ The static keyword cannot be applied to local variables, so it can only act on domains.
① If a field is a static basic type field and it is not initialized, it will obtain the standard initial value of the basic type.
② If it is an object reference, its default initialization value is null.

⭕ Differences in modifiable ranges between static variables and instance variables:

Static variableInstance variable

3.2.4 examples

⭕ Examples of static attributes: ① system out; ② Math.PI;

⭕ Application examples:

🔺 Application example 1:

public class Test1 {
    public static void main(String args[]) {
                Circle c1 = new Circle(2.0);
                Circle c2 = new Circle(3.0);
                c1.display();//name: This is a circle radius:2.0
                c2.display();//name: This is a circle radius:3.0
class Circle {
    private double radius;
    public static String name = "This is a circle";
    public static String getName() {
        return name;
    public Circle(double radius) {
        this.radius = radius; 
    public double findArea() {
        return Math.PI * radius * radius; 
    public void display() {
        System.out.println("name:" + name + "radius:" + radius);

🔺 Application example 2:

class Person {
   private int id;
   public static int total = 0;
   public Person() {
     id = total;
    public static void main(String args[]){
      Person Tom=new Person();;
      total=100; // Static members can be accessed without creating objects

🔺 Application example 3:

public class StaticDemo {
    public static void main(String args[]) { = 100; // Static members can be accessed without creating objects
      //Access method: class name Class attribute, class name Class method
      Person c = new Person();
      System.out.println(; //101

3.2.5 class variable memory parsing

⭕ Illustration 1:

⭕ Illustration 2:

3.3 static modification method

3.3.1 design idea

If the method has nothing to do with the caller, such a method is usually declared as a class method. Since the class method can be called without creating an object, the call of the method is simplified.

3.3.2 understanding

Static modification method is static method.

3.3.3 use

⭕ When there is no instance of an object, you can use the class name Access the class method modified by static in the form of method name ().

⭕ Differences in modifiable scope between static methods and non static methods:

Static methodNon static method

3.3.4 attention

⭕ Because the static method can be accessed without an instance, there cannot be this inside the static method. (nor can there be super)

⭕ static modified methods cannot be overridden.

⭕ In static methods, only static methods or properties can be called.

⭕ In non static methods, you can call either non static methods or properties, or static methods or properties.

3.3.5 examples

public class StaticTest {
	public static void main(String[] args) {		
		Chinese.nation = "China";				
		Chinese c1 = new Chinese(); = "Yao Ming";
		c1.age = 40;
		c1.nation = "CHN";		
		Chinese c2 = new Chinese(); = "Malone";
		c2.age = 30;
		c2.nation = "CHINA";		
		//Compilation failed
// = "Zhang Jike";;;
		//Compilation failed
class Chinese{	
	String name;
	int age;
	static String nation;	
	public void eat(){
		System.out.println("Chinese people eat Chinese food");
		//Call non static structure;
		System.out.println("name :" +name);
		//Call static structure
		System.out.println("nation : " + nation);
	public static void show(){
		System.out.println("I am a Chinese!");
		//Non static structures cannot be called
//		eat();
//		name = "Tom";
		//Static structures can be called
	public void info(){
		System.out.println("name :" + name +",age : " + age);
	public static void walk(){		

4. Attention

⭕ The use of static attributes and static methods can be understood from the perspective of life cycle.

⭕ During development, how to determine whether an attribute should be declared as static?
🔺 Attributes can be shared by multiple objects and will not vary with different objects.
🔺 Constants in classes are also often declared as static.

⭕ During development, how to determine whether a method should be declared as static?
🔺 The method of operating static properties is usually set to static.
🔺 Methods in tool classes are traditionally declared as static. For example: Math, Arrays, Collections.

5. Singleton design mode

5.1 general

⭕ Design pattern is the code structure, programming style and thinking way to solve problems after summarizing and theorizing in a large number of practice. The design of mold eliminates our own thinking and exploration. It's like a classic chess score. We use different chess scores for different chess games. " "Routine"

⭕ The so-called method of obtaining a single class is to ensure the existence of a certain class in the whole system. If we want a class to produce only one object in a virtual machine, what should we do?

① We must first set the access permission of the constructor of the class to private
In this way, you can't use the new operator to generate objects of the class outside the class, but you can still generate objects of the class inside the class.

② Secondly, variables that point to objects of this class generated within the class must also be defined as static
Because you can't get the object of the class from the outside of the class, you can only call a static method of the class to return the object created inside the class. The static method can only access the static member variables in the class. Therefore, the variables pointing to the object of the class generated inside the class must also be defined as static.

5.2 advantages

Since the singleton mode only generates one instance, the system performance overhead is reduced. When the generation of an object requires more resources, such as reading the configuration and generating other dependent objects, it can be solved by directly generating a singleton object when the application is started, and then permanently resident in memory.

5.3 single case design mode - Hungry Han style

class Singleton {
    // 1. Privatization constructor
    private Singleton() {
    // 2. Provide an instance of the current class internally
    // 4. This instance must also be static
    private static Singleton single = new Singleton();
    // 3. Provide a public static method to return the object of the current class
    public static Singleton getInstance() {
    return single; 

5.4 single case design mode - lazy

(1) Singleton design mode - lazy (thread unsafe)

class Singleton {
    // 1. Privatization constructor
    private Singleton() {
    // 2. Provide an instance of the current class internally
    // 4. This instance must also be static
    private static Singleton single;
    // 3. Provide a public static method to return the object of the current class
    public static Singleton getInstance() {
      if(single == null) {
      single = new Singleton();
     return single; 

(2) Singleton design pattern - lazy (thread safe)

public class BankTest {


class Bank{

    private Bank(){}

    private static Bank instance = null;

    public static Bank getInstance(){
        //Mode 1: slightly less efficient
//        synchronized (Bank.class) {
//            if(instance == null){
//                instance = new Bank();
//            }
//            return instance;
//        }
        //Mode 2: higher efficiency
        if(instance == null){

            synchronized (Bank.class) {
                if(instance == null){

                    instance = new Bank();

        return instance;


5.5 application scenarios

⭕ The counter of the website is generally implemented in singleton mode, otherwise it is difficult to synchronize.

⭕ The log application of the application is generally implemented in the single instance mode, which is generally because the shared log file is always open, because there can only be one instance to operate, otherwise the content is not easy to add.

⭕ The design of database connection pool generally adopts single instance mode, because database connection is a kind of database resource.

⭕ In the project, the class that reads the configuration file usually has only one object. There is no need to generate an object to read every time the configuration file data is used.

⭕ Application is also a typical application of singleton.

⭕ The Task Manager of Windows is a typical singleton mode.

⭕ RecycleBin of Windows is also a typical singleton application. During the operation of the whole system, the recycle bin has maintained only one instance.

Tags: Java Eclipse JavaSE jar intellij-idea

Posted by whatever on Sun, 01 May 2022 15:24:57 +0300