Java_ 01_ 002 static keyword

 

static keyword is used to modify member variables and member methods. The modified member belongs to a class, not just an instance object. In other words, since it belongs to a class, it can be called without creating an instance object.

 

◆ static variables

Static variables, also known as class variables, are written equivalent to member variables modified by static keywords.

All objects of the class share the data of the same class variable. Any object can change the value of the class variable of the class, or access or modify the class variable without creating the object of the class.

1. Syntax format

<Permission modifier> static <data type> <Variable name>;

// eg:
static String classroom;
  • The permission modifier is unnecessary, and no modifier is equivalent to default

2. Source code example

Taking students as an example, each student is an independent individual, but many students belong to the same classroom, so the classroom number is taken as its static variable.

public class Student {
    /**
     * Member variable
     */
    private String name;

    /**
     * Static variable
     *
     * Multiple objects share the same data
     */
    public static String classroom;

    public Student(){
        System.out.println("Nonparametric construction method...");
    };
    public Student(String name){
        System.out.println("Full parameter construction method...");
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static String getClassroom() {
        return classroom;
    }

    public static void setClassroom(String classroom) {
        Student.classroom = classroom;
    }
}

 

◆ static method

Static methods, also known as class methods, are written equivalent to member methods modified by static keywords.

1. Syntax format

<Modifier > static <return type> <Method name> (<parameter list>){
	[Method body]
}

// eg:
public static String getClassroom() {
	return classroom;
}
public static void setClassroom(String classroom) {
    Student.classroom = classroom;
}

  • Class methods can directly access class variables and class methods, including itself

  • Class methods cannot directly access ordinary member variables or member methods, but member methods can directly access class variables or static methods, because static contents will be loaded and called in memory first, and then non-static contents will be generated

  • This keyword cannot be used in static methods, because this pointer represents the current object, which is essentially non static content

2. Source code example

/**
* Member method
*/
public void show(){
    System.out.println("Member method...");
    // Member methods can access member variables
    System.out.println(name);
    // Member methods can access static variables
    System.out.println(classroom);

}

/**
* Static method
*/
public static void location(){
    System.out.println("Static method...");
    System.out.println(classroom);

    // Non static variables cannot be accessed directly
    // System.out.println(name);
    // this keyword cannot be used
    // System.out.println(this);
}

 

◆ static code block

Static code block refers to the code block defined at the same level of members and decorated with static keyword.

When the system starts, it is executed only once with the loading of classes, which takes precedence over the execution of all methods including main method and constructor method.

1. Syntax format

static {
	[Execute statement]
}
  • It is generally used to assign initial values to class variables

2. Source code example

/*
 * Static code block
 *
 * When the class is used for the first time, the static code block is executed, and only once
 * In addition, static code blocks always take precedence over non static execution, so static code blocks are executed before construction methods
 *
 * It is generally used to assign a value to a static member variable at one time
 */	
static {
    System.out.println("Static code block execution...");
    classroom = "201";
}

 

◆ test cases

The content of static modification is loaded with the loading of the class, and it is loaded only once. There is a fixed area in memory called static area, which is used to store static content. Therefore, it can be directly called by the class name. Because it has limited existence with objects, it can be shared with all objects of this class.

1. Syntax format

// Access class variables
[Class name].[Class variable name];
[Object name].[Class variable name];
// Static method call
[Class name].[Static method name(parameter list)];
[Object name].[Static method name(parameter list)];

// eg:
Student.classroom;
Student.location();
  • Multiple objects belong to the same class and share the same static content. Therefore, static members can be accessed through the object name, but it is not recommended. This is not only semantically inconsistent, but also warning messages will appear

2. Source code example

import org.junit.Assert;
import org.junit.Test;

/**
 * @author : LiuYJ
 * @version : v1.0
 * @date : Created at 2020/11/5 09:20
 * @date : Modified at 2020/11/5 09:20
 */
public class StudentTest {


    @Test
    public void testBlock() {
        // Static code blocks are executed before the class is used
        System.out.println(Student.classroom);
        Assert.assertEquals("201", Student.classroom);
    }

    @Test
    public void testVariable() {
        // Class variables can be accessed through objects
        Student joyce = new Student("Joyce");
        Assert.assertEquals("Joyce", joyce.getName());
        Assert.assertEquals("201", joyce.classroom);
        joyce.classroom = "205";
        // It is recommended to access by class name instead of object name
        Assert.assertEquals("205", Student.classroom);
    }

    @Test
    public void testMethod() {
        // Class methods can be called through objects
        Student joyce = new Student("Joyce");
        Assert.assertEquals("Joyce", joyce.getName());
        joyce.setClassroom("203");
        Assert.assertEquals("203", joyce.getClassroom());
        // It is recommended to call by class name instead of object name
        Student.setClassroom("203");
        Student.location();
    }
}

All test cases pass and print the following information:

// testBlock
 Static code block execution...
201
    
// testVariable
 Full parameter construction method...

// testMethod 
Full parameter construction method...
Static method...
203

 

◆ application scenarios

Static keyword, which can modify variables, methods and code blocks. In the process of using, the main application still wants to call methods without creating objects. We generally call classes that provide a large number of static methods as tool classes.

Take a guessing game as an example to briefly introduce the powerful functions of the following tools:

  • Generate a random number
  • 10 guessing opportunities, one feedback at a time
  • If you guess right or the opportunity is completely consumed, the game is over
@Test
public void testGuess() {
    double random = Math.random() * 100;
    long actual = Math.round(random);
    boolean isSuccess = false;

    for (int i = 0; i < 10; i++) {
        Scanner scanner = new Scanner(System.in);
        int expected = scanner.nextInt();
        if (expected > actual){
            System.out.println("Too bigger!");
        }else if (expected < actual){
            System.out.println("Too Smaller!");
        }else {
            isSuccess = true;
            System.out.println("Success!");
            break;
        }
    }
    if (!isSuccess){
        System.out.println("Game over!");
    }
}
  • java.lang.Math is a math related tool class. random() can obtain a pseudo-random number between [0.1.0], and round() can obtain the integer closest to the floating point number, which is equivalent to rounding
  • java.util.Scanner is a scanner, through which we can obtain the data entered from the keyboard

 

The above-mentioned words are the words of one family. If there are omissions and fallacies, criticism and correction are welcome!

Tags: Java

Posted by Hokus on Mon, 02 May 2022 07:32:41 +0300