[JavaSE Basics] Underestimate the final keyword Teach you how to deeply understand and use

Hits: 0

📒Blog Homepage: The Steering Blog

🎉Welcome to follow 🔎Like 👍Favorite ⭐️Comment 📝

❤️ : I love Java learning and look forward to communicating with you!

🙏The level of the author is very limited. If you find any mistakes, please let me know, thank you!

🌺 If you have any questions, please send a private message! ! !    

⭐️Small Theater⭐️ _

👻: The following basic rules about java final, which description is wrong?

A. Final modified classes cannot be inherited

B. Final modified member variables are only allowed to be assigned once, and can only be assigned in class methods

The local variables modified by C.final are constants and can only be assigned once.

D. Final modified methods are not allowed to be overridden by subclasses

This is the most basic question and answer question in the final. If you don’t understand the reason, it is recommended to look down. It is full of dry goods. (You can directly pull to the end to see the answer)

Table of contents

⭐️Small Theater⭐️

🌲1. What is final?

🌲1.final modified variable

🌰 1. Final variables point to common data types

🌰2. What is final immutability?

🌰 3.finally modify static variables

🌰 3. final variables point to objects

🌰 3. Immutability difference between final and String

🌲2.final decorating class

🌲3.final modification method

🌲3. Small theater answer and final summary

🌲1. What is final?

final is a basic keyword in Java that can be used to modify classes and methods as well as variables. Its effect is somewhat similar to const in C language. Many people think that final is just immutable in front of variables, and they do not have a deep understanding of the meaning and precautions of the existence of the final keyword. Next, I will analyze its role in variables, methods, and classes.

🌲1.final modified variable

🌰 1.final variables point to common data types

We all know that final modified variables will have immutability, but there are many types of variables. We will not mention what immutability is. Let’s first look at final to modify member variables and local variables without assigning them.   

☀️: We found that when the member variables a and d are declared, if they are not assigned, an error will be reported, which will tell you that they are not initialized in the constructor. But the local variables b and c did not report an error, so we can remember first: the final must be assigned when modifying member variables, and the local variables can be temporarily not assigned.

🌰 2. What is final immutability?

When it comes to immutability, many people must think of String first. But it is different from the immutability of String (final and String can be used together, as will be discussed later). We still use code to demonstrate

Here we use local variables to demonstrate. When we named the b of the final variable, we did not assign a value, and it did not report an error. Then we assigned it a value of 20, and it did not report an error. When we assigned it again, we found that it reported an error. Let’s look at another situation:

On the left, when we directly use b for output without assigning a value to b, we find that the compiler reports an error. But when we assign a value to it, the compiler can call b normally. From the above example, we can draw the conclusion:

✌️: Final modified variables (regardless of member variables or local variables) must be assigned before use, and can only be assigned once. If multiple assignments or no assignments are used, the compiler will prompt an error. 

The above is our macro understanding. We analyze the immutability of final from the perspective of memory :

We enumerate a member variable a and a local variable b. Here is to tell you the difference between them in memory by the way. When we instantiate the class Test7, we have a reference variable a and a value of 100 (the value of the member variable is stored in heap memory). a holds the address of 100, that is, it points to 100. After the local variable b is initialized, a and 10 are generated (the value of the local variable is on the stack), and b points to 10. When we try to make a point to 12 and b to point to 200, that is, when we want to change the addresses of a and b, we find that an error is reported. From this we can know that:

✌️: The immutability of final means that the reference cannot be modified. We all know that the variable itself stores the address of a place, that is, this address cannot be modified. If you point to a place, you can no longer point to another place in your life. This is the meaning of immutability. ( But the content in the pointed address can be modified, be sure to remember!!!, which is different from the immutability of String, which will be explained later )

🌰 3.finally modify static variables

When it comes to variables, static variables must be indispensable. To modify static variables, we usually use static and final in combination, like this format:

public static void main(String[] args) {
        final Student student1;
        student1 = new Student( "Li Si" , 1 );
        student1. ;
        student1.id=2;
        System.out.println(student1);
    }
}

Some people ask what is the advantage of this combination? We combine the characteristics of static and final to know that static variables can be used without objects, and can be called globally. When final is added, it becomes a global constant. Anywhere I call PAI_Value it’s like calling a 3.14. Writing the former code is of course more beautiful and beautiful. This writing format can often be seen when we watch the source code of various methods. Moreover, there are certain specifications for writing in this way, and the underscore should be connected at the beginning of the capital letter.

🌰 3. final variables point to objects

The previous variables point to basic data types. Next, let’s see what is different when final variables point to objects?

We also found that when we assigned another Student instance object to the final modified variable student1 for the second time, it reported an error (here is an example of a local variable)

Also from a memory perspective: when our student1 points to an instance object, it is not allowed to point to another. So can we change the value of Li Si or 1? This refers to the content of the modified address mentioned above, let’s try it

public static void main(String[] args) {
        final Student student1;
        student1 = new Student( "Li Si" , 1 );
        student1. ;
        student1.id=2;
        System.out.println(student1);
    }
}

🎃 : We found that we can change the content of the address pointed to by the final variable, but the address saved by the final variable cannot be changed.

🌰 3. Immutability difference between final and String

Just like this picture, if we have a String a=”hello”, when we write a=”wrold” again, it will not change the original hello to wrold, but change the point of a to point to another string wrold, The original hello cannot be modified. From this we know that if the String object is final modified, it cannot be modified either.

🌲2.final decorating class

The case of final modified classes is relatively rare and the conclusion is relatively simple, so I will give you the conclusion directly and remember:

🔑: 1. Final modified classes cannot be inherited

2. Final cannot modify abstract classes (abstract classes are to be inherited, of course, they cannot be final modified)

3. The class modified by final is generally to prevent others from changing it, such as String

🌲3.final modification method

The same conclusion is drawn first:

🔑: 1. If a method is modified as final, the method cannot be overridden.

2. Final modified methods can be overloaded (be sure to distinguish between overriding and overloading)

3. We use final modification methods, generally to “lock” the method. We don’t want a method to be overridden or rewritten by the subclass after the parent class is inherited by the subclass. We can add final to the method.  

🌲3. Small theater answers and final summary

Now we can clearly understand that the answer of the small theater should be B. ACD are all correct, B is wrong because we only need to assign a value to it before using final, not only in class methods (that is, static methods, according to what it means, static methods can be final modified variable? Ridiculous!). Although final is rarely used in our own code, it is also the basic keyword of Java. It is very common in various source codes. We should master and understand it.

❤️It  is not easy to create, please like and collect if it is useful, and don’t forget to pay attention to Java communication

You may also like...

Leave a Reply

Your email address will not be published.