当前位置:网站首页>Final keyword
Final keyword
2022-07-07 09:20:00 【Wow, it's a small dish】
final This keyword , I usually use a lot , I've seen a lot when I read the source code , But I always forget what this keyword is for . So I came to tidy up for a while .
Catalog
final decorator , Class cannot be inherited
Admittedly, I haven't used it myself final Decorated class ,( used abstract decorator , Design with template strategy ). use final When modifying a class , This class cannot be inherited , Can't be changed .
Common quilt final Decorated classes have these :
- Packaging :Boolean,Character,Short,Integer,Long,Float,Double,Byte,Void( Eight types of packaging types plus one void)
- String class :String,StringBuilder,StringBuffer
- System class :System、Math,StrictMath
These classes are basic classes , Considering safety , They cannot inherit according to the wishes of developers , Change them , Just use final To modify .
final Modification methods , Method cannot be overridden
Even if the subclass inherits the parent , If the method of the parent class is final Modified , Then subclasses cannot override this method .
Use scenarios :
An abstract class is a building , Everyone entering the building should scan the health code , This logic will not change , So use final To define it , Subclasses cannot modify this method according to their own wishes . As for the way to leave this building , Subclasses need to be overridden , Then define freely , Such as walking away , Drive away .
// An abstract class
public class Building {
// final Method
// That is, the subclass executes this method , Nor can you rewrite it to do anything else , Only defined logic can be executed
final void enterBuilding(){
System.out.print(" You need to scan the health code before entering this building ");
}
// Abstract method
// Prepare subclasses to override , The way to customize its logic
abstract void leaveBuilding();
}
public class Skyscraper {
// Override this method
@Override
public void leaveBuilding(){
System.out.print(" Get out of here by walking ");
}
}
final Modify local variables , This variable cannot be changed
Whether formal parameters or actual parameters , By final When decorating , You can no longer modify its value in a method , for example :
public void test(final String str) {
str = " Try to change str";// Report errors , Formal parameters cannot be modified
System.out.println(" This is a str:" + str);
}
public void test2() {
final String str = " Definition str";
str = " Try to change str";// Report errors , The actual parameters cannot be modified
System.out.println(" This is a str:" + str);
}
final When decorating member variables , You need to assign values during initialization , And variables cannot be modified
- Use scenario 1 : There is a variable in a class that has a special meaning , Some methods of this class will use it , also , This variable cannot be changed , Use final Decoration will be safer .
public class TestClass {
// This variable cannot be modified
private int adultAge = 18;
// Other methods will use this variable , meanwhile , This variable has some special meanings , Can't be changed
public void judgeAdult(int age) {
if (age < adultAge) {
System.out.println(" A minor ");
} else {
System.out.println(" adult ");
}
}
}
- Use scenario 2 : and static Use it together , I usually understand it as a constant , It's like enumerating ,( use static Modifier can be class name . Variables directly use ). The function of this variable is No modification is allowed after definition , And use it for many other classes .
public class Constant {
// Use static final To modify the variable , Unwanted new This class can also be used directly
public static final long EXPIRE_DATE = 7200000l;
}
public class TestClass {
public void outOfTime(Date date) {
long currentTimeMillis = System.currentTimeMillis();
if (date.getTime() + Constant.EXPIRE_DATE > currentTimeMillis) {
System.out.println(" The time has expired ~~~");
}
}
}
summary
final Keywords no matter what they decorate , The characteristic is the literal meaning , The final , Not modifiable . When you want your class 、 Method 、 Variables do not change , Not covered by any caller 、 rewrite , that , You can use final Keyword to decorate , Ensure this class 、 Method 、 Variable Security .
边栏推荐
- Self awakening from a 30-year-old female programmer
- Simulation volume leetcode [general] 1557 The minimum number of points that can reach all points
- Chaosblade: introduction to chaos Engineering (I)
- 数据在内存中的存储
- NVIC中断优先级管理
- Locust performance test 5 (analysis)
- Simulation volume leetcode [general] 1567 Length of the longest subarray whose product is a positive number
- Cesium does not support 4490 problem solution and cesium modified source code packaging scheme
- STM32 serial port register library function configuration method
- [istio introduction, architecture, components]
猜你喜欢

寄存器地址名映射

On December 8th, 2020, the memory of marketing MRC application suddenly increased, resulting in system oom

Reflections on the way of enterprise IT architecture transformation (Alibaba's China Taiwan strategic thought and architecture practice)

Locust performance test 4 (custom load Policy)

Connecting mobile phone with ADB

PMP certificate preparation experience sharing

Sublime Text4 download the view in bower and set the shortcut key

Hard core sharing: a common toolkit for hardware engineers

C语言指针(习题篇)

C语言指针(上篇)
随机推荐
华为HCIP-DATACOM-Core_03day
Three updates to build applications for different types of devices | 2022 i/o key review
MySQL master-slave delay solution
How long does the PMP usually need to prepare for the exam in advance?
Confitest of fixture py
[chaosblade: node disk filling, killing the specified process on the node, suspending the specified process on the node]
信息安全实验四:Ip包监视程序实现
Reading notes of pyramid principle
Leetcode question brushing record (array) combination sum, combination sum II
How to pass the PMP Exam in a short time?
Self awakening from a 30-year-old female programmer
JVM 内存结构 详细学习笔记(一)
Jenkins task grouping
串口实验——简单数据收发
Zen - batch import test cases
Unity shader beginner's Essentials (I) -- basic lighting notes
Jenkins+ant+jmeter use
【云原生】DevOps(一):DevOps介绍及Code工具使用
What are the conditions for applying for NPDP?
Troublesome problem of image resizing when using typora to edit markdown to upload CSDN