search
HomeJavajavaTutorialJava Improvement Chapter (14) -----Keyword final

In programming, we sometimes hope that certain data cannot be changed. At this time, final comes into play. Final is a keyword in Java, which means "this part cannot be modified." There are two reasons for not wanting to be changed: efficiency and design. There are three situations where final is used: data, methods, and classes.


##           1. Final data

##                                                     The constancy of data is very useful when it can reduce the burden on the system during runtime. For these constant data, I can call them "constants". "Constant" is mainly used in the following two places:

     

1. Compilation-time constants can never be changed.

​​

2. When initializing during runtime, we hope that it will not be changed. ##​​

For compile-time constants, it has been initialized during the class loading process, so it cannot be changed after the class loading is completed. It can be changed during the compile time It is substituted into any calculation formula that uses it, which means that the calculation formula can be executed at compile time. Of course, for compile-time constants, only basic types can be used, and they must be initialized when defined.

​​​

Some variables, we hope that they can behave differently according to different objects, but at the same time we do not want it to be changed. At this time we can use the runtime constant. For runtime constants, it can be either a basic data type or a reference data type. What is immutable about a basic data type is its content, while what is immutable about a reference data type is its reference, and the content of the object specified by the reference is mutable.

public class Person {
    private String name;

    Person(String name){
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

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

public class FinalTest {
    private final String final_01 = "chenssy";    //编译期常量,必须要进行初始化,且不可更改
    private final String final_02;                //构造器常量,在实例化一个对象时被初始化
    
    private static Random random = new Random();
    private final int final_03 = random.nextInt(50);    //使用随机数来进行初始化
    
    //引用
    public final Person final_04 = new Person("chen_ssy");    //final指向引用数据类型
    
    FinalTest(String final_02){
        this.final_02 = final_02;
    }
    
    public String toString(){
        return "final_01 = " + final_01 +"   final_02 = " + final_02 + "   final_03 = " + final_03 +
               "   final_04 = " + final_04.getName();
    }
    
    public static void main(String[] args) {
        System.out.println("------------第一次创建对象------------");
        FinalTest final1 = new FinalTest("cm");
        System.out.println(final1);
        System.out.println("------------第二次创建对象------------");
        FinalTest final2 = new FinalTest("zj");
        System.out.println(final2);
        System.out.println("------------修改引用对象--------------");
        final2.final_04.setName("chenssy");
        System.out.println(final2);
    }
}

------------------
Output:
------------第一次创建对象------------
final_01 = chenssy   final_02 = cm   final_03 = 34   final_04 = chen_ssy
------------第二次创建对象------------
final_01 = chenssy   final_02 = zj   final_03 = 46   final_04 = chen_ssy
------------修改引用对象--------------
final_01 = chenssy   final_02 = zj   final_03 = 46   final_04 = chenssy



​ ​
The only point explained here is: don’t think that if some data is final, you can know its value at compile time. We will know it through final_03. Here, it is initialized with a random number, and its value can only be known at runtime. .

##, Final Method

All methods that are marked by Final cannot be inherited and changed, so The first reason for using a final method is method locking to prevent any subclasses from modifying it. As for the second reason, it is the efficiency issue. I don’t understand this efficiency issue very clearly. I excerpted this passage from the Internet:

In the early implementation of Java, if a method is designated as final, it means that the compiler agrees to All calls to this method are converted to inline calls. When the compiler finds a final method call command, it will use its own careful judgment to skip the normal calling method of inserting program code and execute the method calling mechanism (push parameters onto the stack, jump to the method code for execution, and then Jump back and clean up the parameters on the stack, handle the return value), and replace the method call with a copy of the actual code in the method body. This will eliminate the overhead of method calls. Of course, if a method is large, your program code will bloat and you may not see the performance gains from inlining because the performance gain will be reduced by the amount of time spent inside the method.

# I don’t understand this passage very well, so I copied it. Can that Java expert explain it to me? !

The final method of the parent class cannot be overridden by the subclass, which means that the subclass cannot have the same method as the parent class. .

public class Custom extends Person{
    public void method1(){
        System.out.println("Person's  method1....");
    }
    
//    Cannot override the final method from person:子类不能覆盖父类的final方法
//    public void method2(){
//        System.out.println("Person's method2...");
//    }
}

3. Final class

If a class is modified with final, it indicates that the class is the final class and it does not want or allow others to inherit it. In programming, for safety or other reasons, we do not allow any changes to this class, and we do not want it to have subclasses. At this time, we can use final to modify the class.

对于final修饰的类来说,它的成员变量可以为final,也可以为非final。如果定义为final,那么final数据的规则同样适合它。而它的方法则会自动的加上final,因为final类是无法被继承,所以这个是默认的。

       四、 final参数

       在实际应用中,我们除了可以用final修饰成员变量、成员方法、类,还可以修饰参数、若某个参数被final修饰了,则代表了该参数是不可改变的。

       如果在方法中我们修改了该参数,则编译器会提示你:The final local variable i cannot be assigned. It must be blank and not using a compound assignment。

public class Custom {
    public void test(final int i){
      //i++;     ---final参数不可改变
        System.out.println(i);
    }
    
    public void test(final Person p){
     //p = new Person();    --final参数不可变
     p.setName("chenssy");
    }
}


       同final修饰参数在内部类中是非常有用的,在匿名内部类中,为了保持参数的一致性,若所在的方法的形参需要被内部类里面使用时,该形参必须为final。详情参看:http://www.php.cn/

       五、final与static

       final和static在一起使用就会发生神奇的化学反应,他们同时使用时即可修饰成员变量,也可修饰成员方法。

       对于成员变量,该变量一旦赋值就不能改变,我们称它为“全局常量”。可以通过类名直接访问。

       对于成员方法,则是不可继承和改变。可以通过类名直接访问。

以上就是java提高篇(十四)-----关键字final 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment