This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

1. Static decorates a member variable

Public class User {public static int onLineNumber; // Instance member variable private String name; private int age; public static void main(String[] args) { //1. Class name, static member variable user.onlinenumber ++; System.out.println(onLineNumber); // 2. Object. Instance member variable User u1 = new User(); U1. name = "ershi "; u1.age = 30; System.out.println(u1.name); System.out.println(u1.age); Static member variable U1.onlinenumber ++; System.out.println(u1.onLineNumber); User u2 = new User(); U2. name = "big brother "; u2.age = 30; System.out.println(u2.name); System.out.println(u2.age); Static member variable u2.onlinenumber ++; System.out.println(u2.onLineNumber); System.out.println(onLineNumber); }}Copy the code

2. Static modifies the memory principle of member variables.

Code in the screenshot

Static member variables are also loaded when the class is loaded.

3. Static decorates the basic use of member methods

public class Student { private String name; private int age; Public void study(){system.out.println (name + "~~ ~~"); 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 (10,100); GetMax (200,20); getMax(200,20); // 2. Object. Example method // study(); Student s = new Student(); S.name = "whole egg "; s.study(); // 3. Object. Static method (not recommended) s.gettmax (10,2); }}Copy the code

  1. Static decorates the memory principles of member methods

When the class is loaded, the static method exposes the calling interface to be invoked

5. Static Example: Use static methods to define utility classes

Public class Login {public static void main(String[] args) {system.out.println (" verification code: "+ VerifyTool. CreteCode (5)); }}Copy the code
Private VerifyTool(){} public static String creteCode(int n){//1. Use to develop a captcha String String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //2. Define a variable to store 5 random characters as 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); } system.out. println(" verification code: "+code); return code; }}Copy the code

The utility class does not need to create objects, and the constructor is private. Let the caller use the class name to call, saving memory.

6. Static Precautions