Thinking in java-19 final、finally、finalize关键字

来源:互联网 发布:伊藤美诚 知乎 编辑:程序博客网 时间:2024/05/29 13:10

这里有关于该问题的stackoverflow问答。

1.final

  • final可以用来修饰一个变量,则表明该变量是不可改变的;
private final String  name = "foo";//the reference name can never change
  • final可以用来修饰一个方法,则表明该方法是不可重写override的;
//The method below can not be overridden by its derived classpublic final String toString(){}
  • final可以用来修饰一个类,则表明该类是不可继承的。
public final class finalClass{    //Some code here.}//The class below is not allowed.public class classNotAllowed extends finalClass{    //some code }

2.finally

finally关键字是用在异常处理时,执行一些总是要完成的工作。在异常发生时,相匹配的catch子句会被执行,然后就进入了finally语句块(如果有的话)。

Lock lock = new ReentrantLock();try{    lock.tryLock();}catch(Exception ex){}finally{    lock.unlock();}

3.finalize

finalize关键字是方法名,当垃圾回收操作发生时,该方法被垃圾回收器调用。一般该方法很少被重写。

protected void finalize(){    //Usually used to free memory    super.finalize();}
package com.fqyuan.thinking;public class Termination {    public static void main(String[] args) {        Book novel = new Book(true);        novel.checkIn();        new Book(true);        /*         * Runs the garbage collector.         *         * Calling the gc method suggests that the Java Virtual Machine expend         * effort toward recycling unused objects in order to make the memory         * they currently occupy available for quick reuse.         */        System.gc();    }}class Book {    boolean checkedOut = false;    Book(boolean checkOut) {        checkedOut = checkOut;    }    void checkIn() {        checkedOut = false;    }    /*     * (非 Javadoc) Called by the garbage collector on an object when garbage     * collection determines that there are no more references to the object. A     * subclass overrides the finalize method to dispose of system resources or     * to perform other cleanup.     *     * @see java.lang.Object#finalize()     */    protected void finalize() {        if (checkedOut)            System.out.println("Error: checked out!");    }}

运行结果:

Error: checked out!

这里写图片描述