Java basics 13 object-oriented ~ static keyword and singleton mode

Like you who love programming!
Learn SpringBoot actual combat course https://edu.csdn.net/course/detail/31433
Learn SpringCloud introductory course https://edu.csdn.net/course/detail/31451


Object-oriented series:
class and object
encapsulation
inherit
polymorphic
static keyword and singleton mode
interface and inner class

Preface

Hello, everyone, in this chapter we introduce two knowledge points: static keyword and singleton mode

static keyword

Static means static, which can be used to modify the attributes and methods of a class. Once the attributes and methods are modified by static, they will be shared by all objects of the class instead of belonging to a certain object.

When certain properties and methods do not want to be called by the object, they can be defined as static.

Static properties

grammar:

static 类型 属性名;

Call of static properties:

类名.属性名
也可以使用:对象名.属性
一般推荐使用类名调用静态成员

The difference between static and non-static attributes

public class StaticTest {
	int count;
	public static void main(String[] args) {
		StaticTest t1 = new StaticTest();
		StaticTest t2 = new StaticTest();
		StaticTest t3 = new StaticTest();
		t1.count++;
		t2.count++;
		t3.count++;
		System.out.println(t1.count);
		System.out.println(t2.count);
		System.out.println(t3.count);
	}
}

The output result is all 1. If count is defined as static, the output result is 3. Why?
to sum up:

  1. Static properties are stored in the method area, and each object shares this static property.
  2. Non-static properties consist of a separate copy of each object.

Non-static properties
Insert picture description here
Static properties
Insert picture description here

Static constant

During the development process, we need some fixed data, such as: Pi 3.1415926

public static final double PI = 3.1415926;

advantage:

  1. High readability
  2. Improve data security
  3. Easy to call and maintain

Static method

definition:

public static 返回值类型 方法名(参数){
}

transfer:

类名.方法名(参数)

note:

  1. Static methods can directly call other static properties and methods of the current class
  2. Static methods cannot directly call the non-static method properties and methods of the current class
  3. Non-static methods can directly call the static and non-static properties and methods of the current class
  4. This and super keywords cannot appear in static methods

Various tool classes in Java use a lot of static methods, such as Arrays, Math, etc.

Static code block

grammar:

static{
	代码块
}

Role:
Initialize static members.
Features:

  1. The static code block is executed only once
  2. Execute after the class is loaded into memory, all code in the class is executed first
  3. In the first use of the class use call

Interview question: the execution result of the following code

public class Test2 {

	//静态代码块
	static{
		System.out.println("这是静态代码块");
	}
	
	//非静态代码块
	{
		System.out.println("这是非静态代码块");
	}
	
	//构造方法
	public Test2(){
		System.out.println("这个构造方法");
	}
	
	public static void main(String[] args) {
		Test2 t1 = new Test2();
		Test2 t2 = new Test2();
		Test2 t3 = new Test2();
	}
}

Insert picture description here
Order of execution:

  1. Static code block (execute only once)
  2. Non-static code block (executed once per object)
  3. Construction method (executed once for each object)

Static import

Features of jdk1.5, after importing a static method of a certain class, you can directly call it without using the class name

//静态导入
import static java.util.Arrays.sort;

public class Test3 {

	public static void main(String[] args) {
		int[] array = {3,5,7,8,2};
		//直接调用
		sort(array);
		for(int n : array){
			System.out.println(n);
		}
	}
}

Singleton mode

The design pattern is a set of solutions summarized by the predecessors for different application requirements. There are 23 common design patterns, also called GOF23.
The singleton mode belongs to the creative mode in GOF23, and its function is to ensure that only one instance of a class can be created

Application scenarios of singleton mode

  1. Certain business scenarios, such as: the company has only one boss
  2. Reduce the consumption of system resources by large objects, such as: connection pool, thread pool

How to implement singleton mode

step:

  1. Define the constructor as private
  2. Define a static object of the singleton class
  3. Define a static method to return a static object

Classification of singletons

Singleton mode is divided into: hungry style and lazy style. The
difference is:

  • Hungry Chinese style, create the object from the beginning
    Advantage: Simple code
    Disadvantage: If the method is not called, it will waste memory
  • Lazy style, do not create the object at first, when the method is called, create the object again.
    Advantages: memory allocation is more efficient.
    Disadvantages: thread safety issues

Hungry Chinese

/**
 * 单例
 */
public class Singleton {
	
	//静态对象
	private static Singleton instance = new Singleton();

	//私有构造方法
	private Singleton(){
	}
	
	//返回对象
	public static Singleton getInstance(){
		return instance;
	}
	
	public static void main(String[] args) {
		Singleton s1 = Singleton.getInstance();
		Singleton s2 = Singleton.getInstance();
		Singleton s3 = Singleton.getInstance();
		System.out.println(s1 == s2);
		System.out.println(s2 == s3);
	}
}

Lazy man

//静态对象
private static Singleton instance = null;

//返回对象
public static Singleton getInstance(){
	if(instance == null){
		instance = new Singleton();
	}
	return instance;
}

Insert picture description here

End

Well, there is so much content in this article, welcome to leave a message to discuss


If you need to learn other Java knowledge, poke here ultra-detailed knowledge of Java Summary

Guess you like

Origin blog.csdn.net/u013343114/article/details/112509898