This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

The article directories

  • final
  • static
    • The static effect
    • The static method
    • Static variables
    • The static block
  • static final

final

Use the final keyword to do the following:

Declare a constant using the final keyword

① The value of a variable is immutable and is called a “constant”.

When a final decorates a primitive datatype, the value of that primitive datatype cannot be changed once initialized, that is, it can only be assigned once. Such as:

final int a = 10; //a = 11; No, the value of A is immutable

(2) When we use final to modify a member variable, we need to define an initial value at the same time. Otherwise, we will report the following error:



This is because the use offinalWhen a keyword modifies a member variable, the Java VIRTUAL machine does not initialize it. Therefore, when we use final to decorate a member variable, we need to define the variable as well as give it an initial value

(3) If a final decorates a reference type, it cannot point to another object after initializing it, but the contents of the object to which the reference refers can change. Such as:

Final Point a = new Point(3,4); //a = null; //a.x = 30; //a.x = 30; Yes, immutable is a, you can’t reassign a

Declare a method using the final keyword

This method is final and can only be inherited by subclasses, but cannot be overridden by subclasses.

The fourth edition of Java Programming Ideas uses the final approach for two reasons. The first reason is to lock a method in case any inherited class changes its meaning; The second reason is efficiency. In earlier versions of The Java implementation, final methods were turned into inline calls. But if the method is too large, you might not see any performance gains from an embedded call. In recent Java releases, the final method is no longer required for these optimizations. “

Therefore, make a method final only if you want to explicitly disallow the method from being overridden ina subclass. Private methods of another class are implicitly specified as final.

Declare a class with the final keyword

That class becomes the final class, the class with no subclasses,finalA decorated class cannot be inherited.

4. Use final ina method parameter. The parameter value cannot be changed inside the method

static

The static effect

The static keyword makes it easy to call (a method/variable) without creating an object. For example, the square root operation we used earlier: math.sqrt (); If the method is not static, we use this method:

Math m = new Math();

m.random;

In other words, we need to create instances and then call methods, which is very inconvenient.

The static keyword has several explanations:

1. Statics belong to classes, not instances

For example, if we modify the soldier class, (using the example from the previous article, Portal: [Darneycourse] Object-oriented Introduction) we add a field count for the number of soldiers:

public class Soldier {
    // Member variables
    int id;// Unique number. Default is 0
    int blood = 100;// The default health is full
    static int count;// Number of soldiers
Copy the code

Where id and blood are allocated one memory address for every Soldier instance they create, and count has only one memory address, which belongs to the class. If two Soldier instances a and b are created and the count value is modified, for example

a.count = 5;
b.count = 6;
Copy the code

So the final value of count is 6.

Static variables modified by static are class variables and can be called by the class name. The variable name is referenced directly, without the need for new to create a class

Static modified methods belong to class methods and can be passed by class name. Method names are referenced directly, without the need for new to create a class

Non-static variables and methods, also called “instance variables” and “instance methods”

3. Use the static keyword to modify a class (inner class), which we’ll see later

4, bestaticDecorated members are loaded into memory first, and memory is freed afterwards, that is, resident memory

2. Use static

public class A {
    public static int a = 10;
    public int b = 20;

    public static void main(String[] args) {
        System.out.println(a);/ / right
        // Because the main method itself is a static method, it enters memory early
        //a = static
        //b is not in memory
        //System.out.println(b); / / error
        
        // But the following is correct
        // After new is executed, the corresponding variable is loaded into memory
        A ss = newA(); System.out.println(ss.b); }}Copy the code

Example 2: Soldier modification

Soldier

public class Soldier {
    // Member variables
    int id;// Unique number. Default is 0
    int blood = 100;// The default health is full
    // Static members
    // Belong to a class, also called a "class variable"
    static int count;// Number of soldiers

    // The constructor
    public Soldier(a) {
        Log.d("Soldiers"."Implemented the construction method of the soldier.");
        // the class name can be omitted, so count++ can also be written;
        Soldier.count++;
    }

    // Member methods
    public void go(TextView tv) {
        if (blood == 0) {
            tv.setText(id + "Dead, unable to advance." + "\n" + tv.getText());
            return;
        }
        tv.setText(id + "Forward" + "\n" + tv.getText());
    }

    public void attack(TextView tv) {
        if (blood == 0) {
            tv.setText(id + "Dead, unable to attack." + "\n" + tv.getText());
            return;
        }

        tv.setText(+id + "The men of the Uss Strike." + "]\n" + tv.getText());

        int b = new Random().nextInt(30);
        if (blood < b) {
            blood = b;
        }
        blood -= b;

        if (blood == 0) {
            tv.setText("[" + id + "No. 1 man killed." + "\n" + tv.getText());
        } else {
            tv.setText("[soldiers" + id + "Attack over, health." + blood + "\n"+ tv.getText()); }}}Copy the code

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Create" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Go" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Attack" />
    
    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Create 5 soldier instances" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Five soldiers attack." />


    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="# 222222"
        android:textSize="20sp" />
</LinearLayout>
Copy the code

MainActivity

public class MainActivity extends AppCompatActivity {
    Button button1;
    Button button2;
    Button button3;
    Button button4;
    Button button5;

    TextView textView;

    Soldier soldier;
    private Soldier[] a;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);
        button4 = findViewById(R.id.button4);
        button5 = findViewById(R.id.button5);
        textView = findViewById(R.id.text);
    }

    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                f1(textView);
                break;
            case R.id.button2:
                f2();
                break;
            case R.id.button3:
                f3();
                break;
            case R.id.button4:
                f4();
                break;
            case R.id.button5:
                f5();
                break; }}private void f1(TextView textView) {
        soldier = new Soldier();
        soldier.id = 9527;
        // Use s1 to find the soldier object memory space
        // Access its property variable id
        textView.setText("Soldier 9527 created" + "\n");
    }

    public void f2(a) {
        soldier.go(textView);
    }

    public void f3(a) {
        soldier.attack(textView);
        textView.setText("Soldiers" + soldier.id + "血量" + soldier.blood + "\n" + textView.getText());
    }

    public void f4(a) {
        // Create an array of 5 lengths and assign it to a
        a = new Soldier[5];
        // Go through the group and put the soldier instance in
        for (int i = 0; i < a.length; i++) {
            a[i] = new Soldier();
            a[i].id = i + 1;
        }
        textView.setText("5 new soldiers have been created");
    }

    public void f5(a) {
        for (int i = 0; i < a.length; i++) {
            a[i].attack(textView);
        }
        textView.setText("Number of soldiers:" + Soldier.count + "\n"+ textView.getText()); }}Copy the code

Running result:

The static method

Methods declared static have several restrictions:

1. They cannot refer to this or super static methods in any way. Static methods are called static methods because static methods do not depend on any object to access them. Because static methods are accessible without relying on any object, there is no way to access non-static member variables and non-static member methods in a static method. Non-static member methods/variables must depend on a specific object to be called

Note, however, that while non-static member methods and non-static member variables cannot be accessed from static methods, static member methods/variables can be accessed from non-static member methods.

Static variables

Static variables are also called static variables. The difference between a static variable and a non-static variable is that a static variable is shared by all objects, has only one copy in memory, and is initialized when and only when the class first loads. A non-static variable is owned by an object, initialized when the object is created, and has multiple copies. The copies owned by each object do not affect each other

Static member variables are initialized in the order they are defined

The static block

Another key use of the static keyword is to form static blocks of code to optimize program performance. Static blocks can be placed anywhere in a class, and there can be multiple static blocks in a class. When the class is first loaded, each static block is executed in the order of the static blocks, and only once.

The reason static blocks can be used to optimize program performance is because they are executed only once, when the class is loaded. For this reason, many times we will initialize something that only needs to be done once in a static block of code. For example, we will write a program to determine whether a person was born between 1946 and 1964:

import java.sql.Date;

class Person {
    private Date birthDate;

    public Person(Date birthDate) {
        this.birthDate = birthDate;
    }

    boolean isBornBoomer(a) {
        Date startDate = Date.valueOf("1946");
        Date endDate = Date.valueOf("1964");
        return birthDate.compareTo(startDate) >= 0 && birthDate.compareTo(endDate) < 0; }}Copy the code

SBornBoomer is used to determine whether the person was born between 1946 and 1964. Each time isBornBoomer is invoked, it generates startDate and birthDate objects, which wastes space.

class Person {
    private Date birthDate;
    private static Date startDate, endDate;

    static {
        startDate = Date.valueOf("1946");
        endDate = Date.valueOf("1964");
    }

    public Person(Date birthDate) {
        this.birthDate = birthDate;
    }

    boolean isBornBoomer(a) {
        return birthDate.compareTo(startDate) >= 0 && birthDate.compareTo(endDate) < 0; }}Copy the code

static final

Static modifiers emphasize that they are only one (memory saving, so that they belong to a class with only one memory address), and final modifiers indicate that they are a constant (cannot be modified after creation). Static final modified properties indicate that once given a value, they are not modifiable and can be accessed by the class name. Static final can also be a modifier to indicate that the method cannot be overridden and can be called without a new object

Static final is a combination of the two, and can be simply understood as a global constant. It is written as follows:

static finalDatatype constant name = value;Copy the code

Note that such constants can only be defined in the class definition block. Only properties of the class are allowed to be defined in this way. This is not allowed in method bodies. The name of a constant is named as follows: All caps, with “_” between the words, for example:

static final int MAX_VALUE = 100;
Copy the code

List of articles: The Static keyword in Java resolves Java object-oriented details