Static keyword: static
Function of static keyword:
- Static means static. It can modify a member variable, which means that only one copy of the member variable is stored in memory and can be shared, accessed and modified.
static modifies member variables:
Member variables can be divided into two categories
-
Static member variable (modified with static, belonging to class, loaded once in memory): it often indicates that information that needs to be shared, such as the number of online people, can be shared and accessed.
-
public class User{ //Static member variable public static String onlineNumber = 161; }
- Class name Static member variables. (recommended)
- Object Static member variables. (not recommended)
-
-
Instance member variables (without static modification, exist in each object): often represent information belonging to each object, such as name, age, and so on.
-
public class User{ public static String onlineNumber = 161; //Instance member variable private String name; private int age; }
- Object Instance member variable
-
package com.csl.d1_static_filed; public class User { //Online population information: static member variable public static int onlineNumber = 161; //Instance member variable private String name; private int age; public static void main(String[] args) { //1. Class name Static member variable User.onlineNumber++; //Note: if static member variables are accessed in the same class, the class name can be omitted without writing System.out.println(onlineNumber); System.out.println(User.onlineNumber); //2. Object Static member variable User u1 = new User(); u1.name = "Sun WuKong"; u1.age = 13; System.out.println(u1.name); System.out.println(u1.age); // Object Static member variables (not recommended) u1.onlineNumber++; User u2 = new User(); u2.name = "Zhu Bajie"; u2.age = 23; System.out.println(u2.name); System.out.println(u2.age); // Object Static member variables (not recommended) u2.onlineNumber++; System.out.println(onlineNumber); } } output: 162 162 Sun WuKong 13 Zhu Bajie 23 164
Memory principle of static modified member variable
Basic usage of static modifier member method
Classification of member methods
- Static member methods (decorated with static, belonging to class) can be accessed by class name or object name.
- Instance member methods (no static modification, belonging to objects) can only trigger access with objects.
Usage scenario
- If it represents the object's own behavior and the method needs to access instance variables, the method must be declared as an instance method.
- If the method is for the purpose of performing a general function or needs to be easily accessed, it can be declared as a static member method.
public class Student { private String name; private int age; /* Instance method: it is an object without static modification. It usually represents its own behavior and can access the member variables of the object */ public void study(){ System.out.println(name+"I am learning!"); } /** * Static method: it is modified by static, belongs to class, and can be accessed by class and object */ public static void getMax(int a,int b){ System.out.println(a > b ? a : b); } public static void main(String[] args) { //1. Class name Static method Student.getMax(100,200); //Note: if static members are accessed in the same class, the class name can be omitted getMax(22,33); //2. Object Example method // study();// Error reporting Student s = new Student(); s.name = "Whole egg,"; s.age = 3; s.study(); //3. Object Static method (not recommended) s.getMax(111,333); } } output: 200 33 Whole egg, learning! 333
Memory principle of static modified member method
Static instance application case: using static methods to define tool classes
Tools:
- For functions that need to be used many times in some applications, these functions can be encapsulated into static methods and placed in a class, which is the tool class
- The function of tool class: first, it is convenient to call, and second, it improves code reuse.
import java.util.Random; public class Login { public static void main(String[] args) { //Verification Code //1. Use String to develop a verification code String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //2. Define a variable to store randomly generated 5-bit characters String code = ""; //3. Circulation Random r = new Random(); for (int i = 0; i < 5; i++) { int index = r.nextInt(chars.length()); //4. Extract characters corresponding to the index code += chars.charAt(index); } System.out.println("The verification code is:"+code); } }
Write as a tool class separately
import java.util.Random; public class VerifyTool { public static String creatCode(int n){ //Using String to develop verification code String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //Define a variable to store the verification code String code = ""; Random r = new Random(); for (int i = 0; i < n; i++) { int index = r.nextInt(chars.length()); code += chars.charAt(index); } return code; } } ---------------------------- public class Register { public static void main(String[] args) { System.out.println(VerifyTool.creatCode(5)); } }
Principle and extension of tools
- Write once and use everywhere
- It is recommended to make the constructor of the tool class private and prevent the tool class from generating objects externally.
import java.util.Random; public class VerifyTool { private VerifyTool(){ } public static String creatCode(int n){ //Using String to develop verification code String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //Define a variable to store the verification code String code = ""; Random r = new Random(); for (int i = 0; i < n; i++) { int index = r.nextInt(chars.length()); code += chars.charAt(index); } return code; } }
Why don't methods in tool classes be written without instance methods?
- Because the instance method needs to create an object to call, the object is only used to call the method, which will only waste memory.
What are tools and what are their benefits?
- There are some static methods inside, and each method completes a function
- Once written, it can be used everywhere to improve the reusability of the code
What are the requirements for tools?
- It is recommended to privatize the constructor of the tool class.
- Tool classes do not need to create objects
static practical application case: defining array tool classes
Requirements: in actual development, we often encounter some tool classes used by arrays. Please write an array tool class as required: ArrayUtils
-
: we know that when an array object is directly output, the address of the object is output, and the contents of the array need to be returned in many places in the project. Please provide a tool class method toString() in ArrayUtils to return the contents of an integer array. The returned string format is as follows: [10,20,40100] (only integer arrays and only one-dimensional arrays are considered)
-
: it is often necessary to count the average value. The average value is the score after removing the lowest score and the highest score. Please provide such a tool method getAevrage to return the average score. (only floating-point arrays and only one-dimensional arrays are considered).
-
Define a test class, call the tool method of the tool class, and return the result
package com.csl.d3_static_test; public class Test { public static void main(String[] args) { int[] arr = {10,20,30,40,50}; System.out.println(arr); System.out.println(ArrayUtils.toString(arr)); System.out.println(ArrayUtils.getAverage(arr)); } }
package com.csl.d3_static_test; public class ArrayUtils { //Constructor privatization processing private ArrayUtils(){ } public static String toString(int[] arr){ if (arr != null){ String result = "["; for (int i = 0; i < arr.length; i++) { result += (i == arr.length-1 ? arr[i] : arr[i] + ","); } result +="]"; return result; }else { return null; } } public static double getAverage(int[] arr){ int max = arr[0]; int min = arr[0]; int sum = 0; for (int i = 0; i < arr.length; i++) { if (arr[i]>max){ max = arr[i]; } if (arr[i]<min){ min = arr[i]; } sum += arr[i]; } return (sum - max - min)*1.0/(arr.length-2); } } output: [I@1b6d3586 [10,20,30,40,50] 30.0
static considerations
- Static methods can only access static members, not instance members directly. (object access can be created in static methods)
- Instance methods can access static members or instance members.
- this keyword cannot appear in static methods.
package com.csl.d4_static_attention; public class Test { //Static member variable public static int age; //Instance member variable public String name; //Static member method public static void getMax(){ //1. Static methods can directly access static member variables System.out.println(age); System.out.println(Test.age); //3. this keyword cannot appear in static methods } //2. Instance methods can directly access static members or instance members public void run(){ System.out.println(age); System.out.println(Test.age); study(); Test.study(); System.out.println(name); sin(); } public void sin(){ System.out.println("I'm singing"); } public static void study(){ System.out.println("I am learning!"); } }
static application knowledge: code blocks
Classification and function of code blocks
Code block overview
- Code block is one of the five major components of a class (member variable, constructor, method, code block and internal class), which is defined outside the method in the class
- In a Java class, the code enclosed by {} is called a code block.
Code blocks are divided into
- Static code block
- Format: static {}
- Features: it needs to be modified by the static keyword. It is loaded with the loading of the class, and it is triggered automatically and executed only once
- Usage scenario: do some static data initialization during class loading for subsequent use.
package com.csl.d5_static_codeblock; public class TestDemo1 { private static String stuName; public static void main(String[] args) { System.out.println("========main Method is executed and output========="); System.out.println(stuName); } /* Features: load together with class, automatically trigger execution once, and give priority to execution Function: it can initialize some static data (prepare content) when the program is loaded */ static { System.out.println("========Static code blocks are triggered for execution========="); stuName = "Chen Taishuai"; } } output: ========Static code blocks are triggered for execution========= ========main Method is executed and output========= Chen Taishuai
- Construct code blocks (understand and use less)
- Format: {}
- Features: each time you create an object and call the constructor for execution, the code in the code block will be executed and executed in the constructor executor.
- Usage scenario: initialize instance resources.
- Format: {}
package com.csl.d5_static_codeblock; public class TestDemo2 { private String name; /* Construct code blocks that belong to objects, load them together with objects, and automatically trigger execution, taking precedence over constructors */ { System.out.println("=========The construction code block is executed=========="); name = "Two eggs"; } public TestDemo2(){ System.out.println("========The constructor is triggered to execute========="); } public static void main(String[] args) { TestDemo2 t = new TestDemo2(); System.out.println(t.name); TestDemo2 t1 = new TestDemo2(); System.out.println(t1.name); } } output =========The construction code block is executed========== ========The constructor is triggered to execute========= Two eggs =========The construction code block is executed========== ========The constructor is triggered to execute========= Two eggs
Application case of static code block
The game called Fighting the Landlord
Requirements:
When starting the game room, 54 cards should be prepared in advance, and these card data can be used directly in the future.
analysis:
- The room only needs a deck of cards
- Define a static ArrayList collection to store 54 card objects, and only one static collection will be loaded.
- Before starting the game, 54 cards should be initialized
- When the system starts, colleagues need to prepare 54 card data, which can be completed with static code blocks.
package com.csl.d5_static_codeblock; import java.util.ArrayList; public class StaticCodeTest { /* Simulate initialization operation Points: "3","4","5","6","7","8","9","10","J","Q","K","A","2"; Decor:“ ♠ "," ♥ "," ♣ "," ♦ "; */ //1. Prepare a container to store 54 card objects. It is recommended to use a static collection, which is loaded only once static ArrayList<String> cards = new ArrayList<>(); /** * 2.Before the game starts, you need to prepare 54 cards to put in and initialize with static code blocks */ static { //3. Load 54 cards and put them in //4. Prepare 4 designs and colors, determine the type and number String[] colors = {"♠", "♥", "♣", "♦"}; //5. Define points String[] sizes = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; //6. Traverse the points first, and then combine the designs and colors for (int i = 0; i < sizes.length; i++) { for (int j = 0; j < colors.length; j++) { cards.add(sizes[i] + colors[j]); } } //7. Add size King cards.add("Xiao Wang"); cards.add("king"); } public static void main(String[] args) { System.out.println("The new brand is:" + cards); } } output: The new brand is:[3♠, 3♥, 3♣, 3♦, 4♠, 4♥, 4♣, 4♦, 5♠, 5♥, 5♣, 5♦, 6♠, 6♥, 6♣, 6♦, 7♠, 7♥, 7♣, 7♦, 8♠, 8♥, 8♣, 8♦, 9♠, 9♥, 9♣, 9♦, 10♠, 10♥, 10♣, 10♦, J♠, J♥, J♣, J♦, Q♠, Q♥, Q♣, Q♦, K♠, K♥, K♣, K♦, A♠, A♥, A♣, A♦, 2♠, 2♥, 2♣, 2♦, Xiao Wang, king]
static applied knowledge: singleton design pattern
Design pattern
What is a design pattern
- Design pattern is a summary of code design experience that has been repeatedly used by predecessors, known by most people and cataloged by classification. Later people can directly use it to solve problems.
- Design pattern is a common solution in soft design. A good design pattern can further improve the reusability of code.
Introduction to singleton mode
Singleton mode:
- It can ensure that there is always only one instance of the class applying this pattern in the system, that is, a class can always create only one object.
Scenario and function of singleton
- For example, we only need one task manager object to solve the problem, which can save memory space.
Hungry man single case mode
- When using the class to get the object, the object has been created for you in advance.
Design steps:
- Define a class and private the constructor.
- Define a static variable to store an object.
package com.csl.d6_static_singleinstance; public class SingleInstance { /* 2.Define an open static member variable to store the object of a class Hungry man: objects will be created when static variables are loaded here public static int onlineNumber = 161; */ public static SingleInstance instance = new SingleInstance(); /* 1.Constructor private */ private SingleInstance(){ } }
Is the test a single case
package com.csl.d6_static_singleinstance; public class Test { public static void main(String[] args) { SingleInstance s1 = SingleInstance.instance; SingleInstance s2 = SingleInstance.instance; SingleInstance s3 = SingleInstance.instance; System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s1==s3); } } output: com.csl.d6_static_singleinstance.SingleInstance@1b6d3586 com.csl.d6_static_singleinstance.SingleInstance@1b6d3586 com.csl.d6_static_singleinstance.SingleInstance@1b6d3586 true
Lazy singleton mode
- Create an object only when the object is really needed (delay loading object)
Design steps:
- Define a class and private the constructor
- Define a static variable to store an object
- Provides a method that returns a singleton object
package com.csl.d6_static_singleinstance; public class SingleInstance2 { /* 1.Constructor privatization */ private SingleInstance2() { } /* 2.Create a static member variable to store the object of this class. Note that the object cannot be initialized at this time */ private static SingleInstance2 instance;//null /* 3.Define a method that can be called elsewhere to get an object */ public static SingleInstance2 getInstance() { if (instance == null) { instance = new SingleInstance2(); } return instance; } }
test
package com.csl.d6_static_singleinstance; public class Test2 { public static void main(String[] args) { SingleInstance2 s1 = SingleInstance2.getInstance(); SingleInstance2 s2 = SingleInstance2.getInstance(); SingleInstance2 s3 = SingleInstance2.getInstance(); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s1 == s3); } } output: com.csl.d6_static_singleinstance.SingleInstance2@1b6d3586 com.csl.d6_static_singleinstance.SingleInstance2@1b6d3586 com.csl.d6_static_singleinstance.SingleInstance2@1b6d3586 true