您的位置:首页 > 编程语言 > Java开发

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

2017-06-18 16:02 399 查看
这里有关于该问题的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!


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息