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

本文详细解释了Java中final、finally与finalize三个关键字的区别与使用场景。final用于定义不可改变的变量、不可重写的方法及不可继承的类;finally用于确保在异常处理过程中始终执行特定代码段;finalize则是对象被垃圾回收前可选的资源释放方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里有关于该问题的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 class
public 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!

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值