1. 程式人生 > >java final 、finally與finalize的區別

java final 、finally與finalize的區別

final在java中,final一般是指不可變的,是一個修飾符,可以修飾常量、方法、類

public class TestOne{
	final int MAX_ONE=1;
	public void test(){
		MAX_ONE=2;//在這裡是錯誤的,變數被final修飾後不能再賦值
	}
	}

public class TestOne{
	final int MAX_ONE=1;
	public final void test(){
		String name="sdf";
	}
	
	
	}
class TestTwo extends TestOne{
	public final void test(){
		String name="sabc";//在這裡是錯誤的,繼承後final方法不能被重寫
	}
	
}
public final class TestOne{
	final int MAX_ONE=1;
	public final void test(){
		String name="sdf";
	}
	
	
	}
class TestTwo extends TestOne{//在這是錯誤的,final類不能被繼承

	
}

finally:finally是異常處理的一部分,

Java 中的 Finally 關鍵一般與try一起使用,在程式進入try塊之後,無論程式是因為異常而中止或其它方式返回終止的,finally塊的內容一定會被執行 。

以下例項演示瞭如何使用 finally 通過 e.getMessage() 來捕獲異常(非法引數異常)

public class ExceptionDemo2 {
   public static void main(String[] argv) {
      new ExceptionDemo2().doTheWork();
   }
   public void doTheWork() {
      Object o = null;
      for (int i=0; i<5; i++) {
         try {
            o = makeObj(i);
         }
         catch (IllegalArgumentException e) {
            System.err.println
            ("Error: ("+ e.getMessage()+").");
            return;   
         }
         finally {
            System.err.println("都已執行完畢");
            if (o==null)
            System.exit(0);
        }
        System.out.println(o); 
      }
   }
   public Object makeObj(int type) 
   throws IllegalArgumentException {
      if (type == 1)  
      throw new IllegalArgumentException
      ("不是指定的型別: " + type);
      return new Object();
   }
}

finalize:finalize-方法名。Java 技術允許使用 finalize() 方法在垃圾收集器將物件從記憶體中清除出去之前做必要的清理工作。

package Initialization;
class Tank{
        int howFull = 0;
        Tank() { this(0);}
        Tank(int fullness){
        howFull = fullness;
}
    void sayHowFull(){
        if(howFull == 0)
        System.out.println("Tank is empty!");
        else
        System.out.println("Tank filling status : " + howFull);
}
    void empty(){
    howFull = 0;
}
    protected void finalize(){
    if(howFull != 0){
    System.out.println("Error: Tank not empty." + this.howFull);
}
//Normally,you'll also do this:
//Super.finalize(); //call the base-class version
}
}
        public class TankTest {
    public static void main(String[] args) {
    Tank tank1 = new Tank();
    Tank tank2 = new Tank(3);
        Tank tank3 = new Tank(5);
    tank2.empty();
        //Drop the reference,forget to cleanup:
    new Tank(6);
        new Tank(7);
    System.out.println("Check tanks:");
        System.out.println("tank1:");
    tank1.sayHowFull();
        System.out.println("tank2:");
    tank2.sayHowFull();
    System.out.println("tank3");
    tank3.sayHowFull();
    System.out.println("first forced gc()");
    System.gc();
    System.out.println("try deprecated runFinalizerOnExit(true)");
    System.runFinalizersOnExit(true);
    System.out.println("last forced gc():");
    System.gc();
}
}