当前位置:网站首页>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 .
边栏推荐
- 串口实验——简单数据收发
- (3/8) method parameters of improper use of enumeration (2)
- [istio introduction, architecture, components]
- 端口复用和重映像
- Locust performance test 2 (interface request)
- C语言指针(下篇)
- Port occupation troubleshooting
- Huawei HCIP - datacom - Core 03 jours
- Mysql database transaction learning notes
- C language pointer (Part 1)
猜你喜欢
外部中断实现按键实验
Reading notes of pyramid principle
JVM garbage collection detailed learning notes (II)
MySQL common statements
PMP Exam Preparation experience systematically improve project management knowledge through learning
Variable parameter of variable length function
NVIC中断优先级管理
Postman setting environment variables
【Istio Network CRD VirtualService、Envoyfilter】
C language pointer (exercises)
随机推荐
[chaosblade: node CPU load, node network delay, node network packet loss, node domain name access exception]
STM32 serial port register library function configuration method
Error: selenium common. exceptions. WebDriverException: Messag‘geckodriver‘ execute
2021 year end summary
What is the rating of Huishang futures company? Is it safe to open an account? I want to open an account, OK?
The essence of high availability
E-commerce campaign Guide
Regular matching starts with XXX and ends with XXX
Record of structured interview
Original collection of hardware bear (updated on May 2022)
Storage of data in memory
Simulation volume leetcode [general] 1557 The minimum number of points that can reach all points
Pytest installation (command line installation)
DRF defines views and routes
Test Engineer Interview Questions 2022
Skill review of test engineer before interview
JVM 垃圾回收 详细学习笔记(二)
十二、排序
What are the suggestions for PMP candidates?
The use of recycling ideas