JavaDay11 static keyword

tags :

  • java Foundation

flag: blue

@toc

JavaDay11 static keyword

I. Introduction of static Keyword

  • Living conditions:
    Water dispensers, for example, are usually placed in a public environment where everyone uses them together. It is not said that everyone enrolls and distributes a water dispenser.
    If everyone has a water dispenser, too many wires, too many water pipes, it takes up a lot of space.

  • Problems in the code:
    It is found that in the code, the values of some member variables are the same, repetitive and exist in every object, such as:
    The countries in the current code are all China. This will take up too much memory resources, even hard disk resources.

  • Expect:
    Put the national Chinese attribute in a shared area and let each object use it.

  • Solve the problem:
    Use the static keyword

static modifies member variables

(1) The use of static keywords:

  • [Focus]
  1. If member variables are modified with static, they are called static member variables. The actual memory space of the static member variables is in the memory data area and has nothing to do with the current class object memory. That is to say, this static member variable is no longer in object memory using memory space.

  2. static-modified member variables, which can be used by multiple class objects.

  3. When to use static, there is a lot of duplication in the true sense, and there is some sharing of basic data, in this case, you can use static to modify.
    For example, the count attribute is suitable for static modification, but the name attribute is not.

  • A minor question:
    It is found that the class object is used to call the static member variable and give an alarm.
    The static field Person.country should be accessed in a static way
    Static-modified static member variables should be accessed in a static manner

  • [Focus]
    A member variable modified with static is created [earlier than] the creation of class objects and destroyed [later than] the destruction of class objects. So, static member variables are "unrelated" to class objects, where "unrelated" refers to: first, memory is unrelated, and then has nothing to do with the creation of objects.

    Strictly speaking, class objects are not related to static member variables, so it is "illegal" to call static member variables through class objects.
    What the Java language expects is a more rigorous way of invoking, because it has nothing to do with the object, so it doesn't want to call it.
    [Recommended way to call/use member variables] class name. member variables;
    There's no warning. It's also a reminder that static modifies the static member variables and has nothing to do with class objects.

    [Amendment issues]
    Static-modified member variables, no matter which way memory is modified, all the data used for this static member variable will change.

    Because [static member variables] are a [implied shared resource]
    For example:
    Put a piece of sugar in the well, you can taste the sweetness.

Sample code:

class Person {
	//Membership variables
	private String name;    //Full name
	
	//Here is the member variable modified with static
	static String country = "China"; //Country
	
	//Construction method
	public Person() {}
	
	public Person(String name) {
		this.name = name;
	}
	
	//setter and getter methods
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
}


public class Demo1 {
	public static void main(String[] args) {
		Person p1 = new Person("Ye Wen"); //4		
		Person p2 = new Person("Chan Wah Shun"); //4 		
		Person p3 = new Person("Chen Zhen"); // 4		     
		Person p4 = new Person("Lee Hoon Leong"); // 4
		
		System.out.println("p1.country:" + p1.country);
		System.out.println("p2.country:" + p2.country);
		Person.country = "China"; //Recommendation
		p3.country = "People Republic of China";
		System.out.println("p3.country:" + p3.country); // PRC 
		System.out.println("p4.country:" + p4.country); // China
	}
}

3. static Modified Membership Method

Static modifies member methods, which are called static member methods

Format:

Permission modifier static return value type method name (formal parameter list){
           Method body;
}
  • [Focus]
    Static modified membership method is called static membership method, which is earlier than object creation and loading, and still exists after object destruction. Because methods and functions are placed in the code area and loaded into it, [static member methods] have nothing to do with objects.

If class object is used to call [static member method], the alarm will be given:
The static method sleep() from type Dog should be accessed in a static way
sleep() in the Dog class should be called statically

  • [Notes]
  1. this keyword cannot be used in the static member method modified with static
    Result deduction:
    Because [static member method] can be invoked by class name, there is no object in the case of class name invocation, and this keyword is used to represent the object keyword of invoking this method, there is no object, so it can not be used.
    Principle deduction:
    Because [static member method] is earlier than object loading and later than object destroying, it has nothing to do with the object, whether there are objects or not, this method exists, so this keyword can not be used here.

  2. In static modified static member method, non-static member variables cannot be used because they are stored in the memory of class objects and coexist with class objects, while there are no objects in the process of invoking static member methods, so non-static members cannot be used. Variables]

  3. [Static Membership Method] can be used directly [Static Membership Variables]

  4. What if you want to use a non-static member variable in the Static Membership Method?
    You can use the new keyword in the current [static member method], call the construction method, create an object, and use the object.
    Case:
    Singleton Design Patterns

[Summary]
Static versus static, non-static versus non-static

[Static Membership Method Usage]
1. It is convenient to call this method directly by class name without resorting to objects.
2. Used to complete some [tool classes]
Arrays Tool Class

Sample code:

class Dog {
	//Membership variables
	private String name;
	
	//[Static member variables]
	static String country = " JP ";
	
	//Construction method
	public Dog() {}
	
	public Dog(String name) {
		this.name = name; 
	}
	
	//setter and getter methods
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	//Membership method
	public void run() {
		this.name = "ll"; //Calling non-static member variables with this keyword
						  //This represents the object that calls this method
		name = "lxl"; //Non-static member variables
		country = "Janp"; //Static member variables
		System.out.println("Running around~~~");
	}
	
	//Static Membership Method
	public static void sleep() {
		//this.name = "ll"; Cannot use this in static context  WHY
		country = "RB"; //Static member variables
		//name = "gz"; // WHY
		System.out.println("sleep a lot~~~~");
	}
	
	// Using non-static member variables in static member methods
	public static void test() {
		Dog dog = new Dog("Dog");		
		System.out.println(dog.name);
	}
}

public class Demo2 {
	public static void main(String[] args) {
		Dog dog = new Dog("Bobo");
		
		dog.sleep();
		Dog.sleep();
		
		Dog.test();
	}
}

IV. Use of Static Membership Variables

See Demo3.java for details
Usually used in counters

package com.qfedu.a_static;

/*
	Use cases of static member variables:
  		Statistics on how many objects a class creates
  		Population Statistics, Data Statistics, ID Automatic Generation
  		
  	ID After creating objects, they are automatically assigned, and the ID number of each object is unique and incremental.
 */

class Student {
	private int id; //This ID number is used to count students. This ID is considered to be automatically generated.
	private String name;
	private char sex;
	
	//A [static member variable] in the data area is used to store count's data, and it is privatized to provide nothing outside the class.
	//How to modify or obtain the data
	//If the program stops, there will be a recount without data persistence.
	private static int count = 1;
	
	//Construct blocks of code that any object will execute
	{
		this.id = count++;
	}
	
	public Student() {}
	
	//Because ID is automatically generated by the current program, there is no need to pass parameter assignment by construction method.
	public Student(String name, char sex) {
		this.name = name;
		this.sex = sex;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setSex(char sex) {
		this.sex = sex;
	}
	
	public char getSex() {
		return sex;
	}
	//ID does not want external modifications or permissions, so it does not provide setter methods after encapsulation, but only a view function getter method.
	public int getId() {
		return id;
	}
	
	
}

public class Demo3 {
	public static void main(String[] args) {
		Student stu1 = new Student();
		System.out.println(stu1.getId());
		
		Student stu2 = new Student();
		System.out.println(stu2.getId());
		
	}
}

V. The Use of Static Membership Method

package com.qfedu.a_static;

/*
	Use cases of static member variables:
  		Statistics on how many objects a class creates
  		Population Statistics, Data Statistics, ID Automatic Generation
  		
  	ID After creating objects, they are automatically assigned, and the ID number of each object is unique and incremental.
 */

class Student {
	private int id; //This ID number is used to count students. This ID is considered to be automatically generated.
	private String name;
	private char sex;
	
	//A [static member variable] in the data area is used to store count's data, and it is privatized to provide nothing outside the class.
	//How to modify or obtain the data
	//If the program stops, there will be a recount without data persistence.
	private static int count = 1;
	
	//Construct blocks of code that any object will execute
	{
		this.id = count++;
	}
	
	public Student() {}
	
	//Because ID is automatically generated by the current program, there is no need to pass parameter assignment by construction method.
	public Student(String name, char sex) {
		this.name = name;
		this.sex = sex;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setSex(char sex) {
		this.sex = sex;
	}
	
	public char getSex() {
		return sex;
	}
	//ID does not want external modifications or permissions, so it does not provide setter methods after encapsulation, but only a view function getter method.
	public int getId() {
		return id;
	}
	
	
}

public class Demo3 {
	public static void main(String[] args) {
		Student stu1 = new Student();
		System.out.println(stu1.getId());
		
		Student stu2 = new Student();
		System.out.println(stu2.getId());
		
	}
}


See Demo 4. Java and Demo 5. Java for details
Usually made into tool classes

package com.qfedu.a_static;

import java.util.Arrays;

/*
  Use of static member methods
  	
  	Make a tool class for developers to use, more convenient, easy to call, get rid of the constraints of class objects, and all the data is
  	Caller incoming has nothing to do with the member variables in the tool class, or even some tool classes have no member variables.
  	
  	Arrays Tool class, which provides a large number of methods for array manipulation, and all the methods in Array Tool class
  	They're all decorated with public statistics.
  	
  	sort  toString  binarySearch
 */

public class Demo4 {
	public static void main(String[] args) {
		int[] arr = {1, 9, 3, 4, 2, 8, 10, 5, 7, 6};
		
		//Using the sort method in the following Arrays tool class, the sorting algorithm defaults to small to large, ascending order.
		Arrays.sort(arr);
		
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		
		//The toString method in the Arrays tool class, whose return value is a String type
		//For example: {1, 2, 3}=> [1, 2, 3]
		String arrString = Arrays.toString(arr);
		System.out.println(arrString);
		
		//The binary Search in the Arrays tool is a way to find data, requiring that the array data to be searched must be sorted through the array.
		//And it returns the subscript where the data is currently looking for. If it is not found, it returns the negative number and the valid subscript value.
		int index = Arrays.binarySearch(arr, 5);
		System.out.println("index =" + index);
	}
}

6. Custom Tool Class

Complete MyToString(int[] arr) and MyReverse(int[] arr)

Chat with main function

class Demo6 {
      public static void main(String[] args) {
	
  	}
}
  • public: Privilege access modifier, open, with the highest privilege and the highest degree of freedom. It is convenient for JVM to find main function directly under any circumstances.
    Start running the current program, the only entry to the main function program

  • static: Statically modifies keywords. Calling main function does not require the participation of objects. It can be called directly by class name, which facilitates the process of JVM calling main function.
    Physical truth:
    Demo6.main(null); //JVM

  • void: There is no return value. The main function is special. The return value is meaningless for the main function because the main function caller is JVM and JVM does not need it.
    This return value

  • main: function name, well-known function name, most languages have this function name, indicating that the only entry to the current program supports C++ C OC

  • (String [] args): The main function runs on a list of parameters, the type of which is a String [] an array of strings.
    args is the abbreviation of arguments.~~~

8. Array Supplementary Knowledge

ArraryIndexOutOfBoundsException array subscript crosses the bounds [exception], usually the operand array subscript exceeds the valid subscript range of the array.
NullPointerException null pointer exception, operation null memory space exception

Keywords: Java jvm Attribute P4

Added by blackswan on Fri, 23 Aug 2019 14:13:26 +0300