当前位置:网站首页>I have something to say about final, finally and finalize

I have something to say about final, finally and finalize

2022-06-11 14:08:00 sniper_ fandc

final

final Keywords are used to decorate classes 、 Method 、 Variable .

1. When a class is decorated, it means that the class cannot be inherited , It is mainly used to consider the security of classes . Attention should be paid to , One final Member methods of a class are implicitly defined as final Method .

2. When decorating a method, the representation cannot be overridden , Subclasses can inherit , But you can't rewrite it .

3. When you modify a variable, it means that the variable is a constant , That is, it can only be explicitly assigned once during initialization , Cannot be reassigned .

finally

be chiefly used in try-catch The last resource release in exception capture , Some people here think finally The statement must be executed to , Let's look at the following code :

//1.try-catch Abnormal exit 
try {
    System.exit(1)
} catch {
    ....
} finally {
	// It's not going to work here 
    Log.d("finally", "finally");
}

//2. Infinite loop 
try {
    while(true) {
        ...
    }
} finally {
    // It's not going to work here 
    Log.d("finally", "finally");
}

//3.  Thread killed 
// When executed  try-catch  when , The thread was killed , that  finally  The code in can't be executed to 

finalize

This method is included in Object class , It is mainly called when the object is recycled , Do some resource release work . But use finalize Attention is also needed , call super.finalize(), Of an object finalize() Methods are called only once , and finalize() Being called does not mean that the object will be reclaimed immediately , So it's possible to call finalize() after , The object doesn't need to be recycled again , And then it's time to actually recycle , Because I called it once before , So it won't call finalize(), A problem . therefore , It is not recommended to use finalize() Method .

原网站

版权声明
本文为[sniper_ fandc]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012052375437.html