当前位置:网站首页>Deeply analyze the usage of final keyword
Deeply analyze the usage of final keyword
2022-06-22 08:40:00 【BreezAm】
Fu Taogong
Cool breezeThrough the ages , Who else is Yu , How dare you call me
Personal blog address :http://blog.breez.work
List of articles
Introduce
final For declaration attribute 【 Properties are immutable 】、 Method 【 Method cannot be overridden 】、 class ( Except for abstract classes )【 Class cannot be inherited 】
analysis
final attribute
By final Embellished
Variable is immutable.【Reference immutable】
public class FinalTest {
public static void main(String[] args) {
final StringBuffer s = new StringBuffer("Hello");
s.append(" World");
System.out.println(s); // Output Hello World
}
}
public class FinalTest {
public static void main(String[] args) {
final StringBuffer s = new StringBuffer("Hello World");
s = new StringBuffer("Hello world"); // Compiler error
}
}
As can be seen from the above final refer to Reference immutable , That is, it can only point to the one pointed to during initialization object , Don't care about pointing to objects Content The change of . So be final Embellished Variable Must be initialized .
How to initialize :
- Initialize at definition time
final String name="BreezAm";
name="change"; // Compile error
- final Member variables can be set in
In initial blockinitialization , But it cannot be initialized in a static block .
- Initialize... In the initialization block :【
Compile and pass】
public class FinalTest {
private final String name;// Define a member variable
{
name = "BreezAm";// Initialize member variables in the initialization block name
}
public static void main(String[] args) {
FinalTest test = new FinalTest();
String name = test.name;
System.out.println(name);//BreezAm
test.name="change";// Compiler error
}
}
Try to be in Static initialization block In the initialization final Variable 【 Compiler error 】
public class FinalTest {
private final String name;// Compiler error
static{
name = "BreezAm"; // Compiler error , Even if the name It has been initialized during definition, and an error will be reported during compilation
}
public static void main(String[] args) {
FinalTest test = new FinalTest();
String name = test.name;
System.out.println(name);//BreezAm
}
}
static statefinal Member variables can be set inStatic initialization blockIn the initialization , But not inInitialization blockIn the initialization .
- stay
Static initialization blockInitializing member variables in 【Compile and pass】
public class FinalTest {
private static final String name;// Define a static 、 Immutable variables
static {
name = "BreezAm";// Initialize... In a static initialization block
}
public static void main(String[] args) {
String name = FinalTest.name;
System.out.println(name);//BreezAm
}
}
- Try to be in
Static initialization blockInitializing member variables in 【Compiler error】
public class FinalTest {
private static final String name;// Compiler error
{
name = "BreezAm";// Initialize... In the initialization block
}
public static void main(String[] args) {
String name = FinalTest.name;
System.out.println(name);//BreezAm
}
}
- In class
ConstructorsIn the initialization , butstatic state final Member variablesCan not be Initializes in the constructor .
- stay
ConstructorsIn the initializationThe staticfinal Member variables 【Compile and pass】
public class FinalTest {
private final String name;// Define a member variable 【 uninitialized 】
public FinalTest() {
name = "BreezAm";// Initialize... In the constructor final A member variable of type
}
public static void main(String[] args) {
FinalTest test = new FinalTest();
String name = test.name;
System.out.println(name);//BreezAm
}
}
final Method
When a method is declared as final when , The method
No subclasses are allowed to overrideThis method , butSubclasses can still useThis method .[Be careful:final Methods can be overloaded ]
in addition , There is another one called
inline( inline )The mechanism of , When a call is declared as final Method time , Direct the method bodyInsert into the callout, Instead of making method calls ( Be similar to C++ Medium inline), To do so Can improve the efficiency of the program .
Case study :
/** * Parent class */
public class Father {
/** * Write a final Method */
public final void doAction(){
System.out.println(" I am a final Method 、 I can't be rewritten , But you can use Oh ! Cinderella !!");
}
}
Subclasses attempt to override final Method 【 Compiler error 】
/** * Subclass */
public class Children extends Father {
public final void doAction(){
// Compiler error 、 Because the parents doAction The method is final Type of , So it can't be rewritten
}
public static void main(String[] args) {
}
}
Use... In the parent class final Method 【 Compile and pass 】
/** * Subclass */
public class Children extends Father {
public static void main(String[] args) {
Children children = new Children();
children.doAction();
}
}
Output :
I am a final Method 、 I can't be rewritten , But you can use Oh ! Cinderella !!
Subclasses overload... In the parent class final Method
/** * Subclass */
public class Children extends Father {
/** * Override the parent class declared as final Methods * @param a * @param b */
public final void doAction(int a,int b){
// It can be reloaded , ha-ha , I found out
System.out.println("a:"+a);
System.out.println("b:"+b);
}
public static void main(String[] args) {
Children children = new Children();
children.doAction(20,30);
}
}
Output :
a:20
b:30
final Parameters
Used to express this
ParametersIn thisInternal functionNot allowed to be modified
Case study :
public class FinalTest {
/** * Write a program with parameters as final Methods * * @param name */
/*public void doActionFinal(final String name) { name = " I want to change name, But the compilation report is wrong , sorry !!"; // Compile not pass }*/
/** * Write a non - final Parameter method * * @param name */
public void doAction(String name) {
System.out.println(" Before the change :" + name);
name = "name The parameter is not final Of , I modified it successfully , One word : Bashi !"; // Compile and pass
System.out.println(" After modification : " + name);
}
public static void main(String[] args) {
FinalTest test = new FinalTest();
//test.doActionFinal("BreezAm");
test.doAction("BreezAm");
}
}
Output :
Before the change :BreezAm
After modification : name The parameter is not final Of , I modified it successfully , One word : Bashi !
final class
When a class is declared final when , Such kind
uninheritable, All the methods areCan't be rewritten. But this It doesn't mean final Class member variables are also immutable , To do it final The member variables of a class cannot be changed , Member variables must be givenincrease final modification. Be careful : A class cannot be declared as abstract, It was declared that final【Abstract classes cannot be declared as final】.
An attempt to inherit is declared as final Class 【 Compile failed 】
/** * Parent class */
public final class Father {
}
/** * Subclass */
public class Children extends Father {
// Compiler error
}
Try to put a abstract Class declared as final【 Compile failed 】
/** * Parent class */
public final abstract class Father {
// Compile failed , Abstract classes cannot be declared as final
}
modify final Member variables of class
/** * Parent class */
public final class Father {
private String name = "BreezAm";
private final int num = 2018010110;
public void doAction() {
name = " Cool breeze ";// modify final Class's non final Member variables Compile and pass
num = 2019010110;// modify final Class final Member variables Compile failed
}
}

边栏推荐
- Web Knowledge 2 (request+response)
- 学科融合对steam教育的作用
- 矩阵分解
- 培养以科学技能为本的Steam教育
- Questions 101 to 200 of the national information security grade examination nisp level 1 question bank (1)
- MySQL sub database and sub table
- 【自适应控制】最小二乘法离线辨识
- 面试突击59:一个表中可以有多个自增列吗?
- Distributed transaction
- Mysql+orcle (SQL implements recursive query of all data of child nodes)
猜你喜欢

深入理解MySQL索引凭什么能让查询效率提高这么多?

Eureka的InstanceInfoReplicator类(服务注册辅助工具)

10.File/IO流-bite

报告:在技术领域,男性更有可能获得工作面试的机会

Basic concepts of homomorphic encryption

Crawling microblog comments | emotional analysis of comment information | word cloud of comment information

Thoroughly understand my SQL index knowledge points

Web knowledge 3 (cookie+session)
![[path planning] auxiliary points and multi segment Bessel smoothing RRT](/img/0c/74055c93a11b9be18dfec1058796c2.jpg)
[path planning] auxiliary points and multi segment Bessel smoothing RRT

The necessity of steam education culture inheritance
随机推荐
yolov5 export Gpu推理模型导出
Thread.start()方法源码分析
07 适配器模式
Introduction to bee's main functions and features
How to select the appropriate partition key, routing rule and partition number
AQS learning notes
Android kotlin Camera2预览功能实现
Thoroughly understand my SQL index knowledge points
18 intermediary model
Eureka的InstanceInfoReplicator类(服务注册辅助工具)
A simple - timed task component (quartz) -demo
一文搞懂one-hot和embedding
[conda]conda切换为中科大源
Bee framework, an ORM framework
[conda]conda switch to source of China University of science and technology
09 组合模式
Enumerations, custom types, and swaggerignore in swagger
Several methods to prevent repeated form submission + actual measurement
11 外观模式
20 status mode
