在Java中,关键字“final”、“finally”和“finalize”有什么作用?

发布于 2024-12-11 05:26:50 字数 1436 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

南…巷孤猫 2024-12-18 05:26:50

Final

final 可以用来标记一个变量“不可更改”

private final String name = "foo";  //the reference name can never change

final 也可以使一个方法不可“重写”

public final String toString() {  return "NULL"; }

final 还可以使一个类不可“ 重写” “可继承”。即该类不能被子类化。

public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

finally

finally 在 try/catch 语句中使用,以始终执行代码"

lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}

Java 7 有一个新的 try with resources 语句,您可以使用它自动关闭显式的资源或隐式实现 java.io.Closeablejava.lang.AutoCloseable

Finalize

finalize 当对象被调用被垃圾收集。您很少需要覆盖它。一个例子:

protected void finalize() {
  //free resources (e.g. unallocate memory)
  super.finalize();
}

final

final can be used to mark a variable "unchangeable"

private final String name = "foo";  //the reference name can never change

final can also make a method not "overrideable"

public final String toString() {  return "NULL"; }

final can also make a class not "inheritable". i.e. the class can not be subclassed.

public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

finally

finally is used in a try/catch statement to execute code "always"

lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}

Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable

finalize

finalize is called when an object is garbage collected. You rarely need to override it. An example:

protected void finalize() {
  //free resources (e.g. unallocate memory)
  super.finalize();
}
时光沙漏 2024-12-18 05:26:50
  • “最终”表示某些事情无法改变。您通常希望在静态变量上使用它,这些变量在程序的整个生命周期中保持相同的值。
  • “Finally”与 try/catch 块结合使用。无论“try”块中的代码是否抛出异常,“finally”子句中的任何内容都将被执行。
  • “Finalize”是在对象即将被垃圾收集之前由 JVM 调用的。
  • "Final" denotes that something cannot be changed. You usually want to use this on static variables that will hold the same value throughout the life of your program.
  • "Finally" is used in conjunction with a try/catch block. Anything inside of the "finally" clause will be executed regardless of if the code in the 'try' block throws an exception or not.
  • "Finalize" is called by the JVM before an object is about to be garbage collected.
昔日梦未散 2024-12-18 05:26:50

Final关键字用于声明常量。

final int FILE_TYPE = 3;

finally 关键字在 try catch 语句中使用,用于指定要执行的代码块,无论是否抛出异常。

try
{
  //stuff
}
catch(Exception e)
{
  //do stuff
}
finally
{
  //this is always run
}

最后(哈哈),finalize 我不完全确定是一个关键字,但是有一个 finalize( ) Object 类中的函数。

The final keyword is used to declare constants.

final int FILE_TYPE = 3;

The finally keyword is used in a try catch statement to specify a block of code to execute regardless of thrown exceptions.

try
{
  //stuff
}
catch(Exception e)
{
  //do stuff
}
finally
{
  //this is always run
}

And finally (haha), finalize im not entirely sure is a keyword, but there is a finalize() function in the Object class.

成熟的代价 2024-12-18 05:26:50

http://allu.wordpress.com/ 2006/11/08/final-finally-和-finalize之间的差异/

final – 常量声明。

finally –finally 块总是在 try 块退出时执行,除了 System.exit(0) 调用。这确保即使发生意外异常,finally 块也会被执行。但finally 的用途不仅仅是异常处理——它允许程序员避免清理代码被返回、继续或中断意外绕过。将清理代码放在finally 块中始终是一个很好的做法,即使在预计不会出现异常的情况下也是如此。

finalize() – 方法有助于垃圾收集。在垃圾收集器丢弃对象之前调用的方法,允许其清理其状态。不应该用于释放非内存资源,如文件句柄、套接字、数据库连接等,因为 Java 只有有限数量的这些资源,并且您不知道垃圾收集何时开始释放这些非内存资源通过finalize()方法。

您是否尝试在谷歌上搜索,并需要澄清解释?

http://allu.wordpress.com/2006/11/08/difference-between-final-finally-and-finalize/

final – constant declaration.

finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Did you try searching on google, and need clarification for an explanation?

温暖的光 2024-12-18 05:26:50

最终的:
final 是一个关键字。 声明为final 的变量应该是
仅初始化一次且无法更改。 Java类
声明为最终版本的不能延期。声明为最终方法
不能被覆盖。

最后:
finally 是一个块。finally 块总是在以下情况下执行:
尝试阻止出口。这确保了finally块被执行
即使发生意外的异常。但最终有用的是
不仅仅是异常处理——它允许程序员
避免清理代码被返回意外绕过,
继续,或者中断。将清理代码放入finally块中是
即使没有预期到例外,这始终是一个好的做法。

最终确定:
finalize 是一个方法。在对象被垃圾回收之前,
运行时系统调用其finalize()方法。可以写系统
资源在获取垃圾之前在 Finalize() 方法中释放代码
集。

final:
final is a keyword. The variable decleared as final should be
initialized only once and cannot be changed. Java classes
declared as final cannot be extended. Methods declared as final
cannot be overridden.

finally:
finally is a block. The finally block always executes when the
try block exits. This ensures that the finally block is executed
even if an unexpected exception occurs. But finally is useful for
more than just exception handling - it allows the programmer to
avoid having cleanup code accidentally bypassed by a return,
continue, or break. Putting cleanup code in a finally block is
always a good practice, even when no exceptions are anticipated.

finalize:
finalize is a method. Before an object is garbage collected, the
runtime system calls its finalize() method. You can write system
resources release code in finalize() method before getting garbage
collected.

陌伤浅笑 2024-12-18 05:26:50

1.决赛
• Final 用于对类、方法和变量应用限制。
• Final 类不能被继承,final 方法不能被覆盖,final 变量值不能被改变。
• Final 变量在创建时初始化,但在构造函数中初始化的空白final 变量除外。
• Final 是一个关键字。

2.最后
• Final 与try 和catch 一起用于异常处理。
• 无论是否处理异常都会执行。
• 该块用于关闭数据库连接、I/O 资源等资源。
• 最后是一个块。

3.最终确定
• Finalize 由垃圾收集线程在收集符合条件的对象以执行清理处理之前调用。
• 这是对象执行任何清理的最后机会,但由于不能保证是否会调用finalize(),因此在finalize 调用之前保留资源是不好的做法。
• Finalize 是一种方法。

1. Final
• Final is used to apply restrictions on class, method and variable.
• Final class can't be inherited, final method can't be overridden and final variable value can't be changed.
• Final variables are initialized at the time of creation except in case of blank final variable which is initialized in Constructor.
• Final is a keyword.

2. Finally
• Finally is used for exception handling along with try and catch.
• It will be executed whether exception is handled or not.
• This block is used to close the resources like database connection, I/O resources.
• Finally is a block.

3. Finalize
• Finalize is called by Garbage collection thread just before collecting eligible objects to perform clean up processing.
• This is the last chance for object to perform any clean-up but since it’s not guaranteed that whether finalize () will be called, its bad practice to keep resource till finalize call.
• Finalize is a method.

忱杏 2024-12-18 05:26:50

java中final的含义是:
-应用于变量意味着相应的变量一旦初始化就不能再修改。

private final double numer = 12;

如果您尝试修改此值,您将收到错误。

- 应用于方法意味着相应的方法不能被重写,

 public final void displayMsg()
    {
        System.out.println("I'm in Base class - displayMsg()");
    }

但final方法可以被继承,因为final关键字限制了方法的重新定义。

-应用于一个类意味着相应的类不能被扩展。

class Base
{

    public void displayMsg()
    {
        System.out.println("I'm in Base class - displayMsg()");
    }
}

finally 的含义是:

class TestFinallyBlock{  
  public static void main(String args[]){  
  try{  
   int data=25/5;  
   System.out.println(data);  
  }  
  catch(NullPointerException e){System.out.println(e);}  
  finally{System.out.println("finally block is always executed");}  
  System.out.println("rest of the code...");  
  }  
} 

在这个例子中,无论 try-catch 是否被执行,finally 里面的内容都会被执行。
Finalize的含义:

class FinalizeExample{  
public void finalize(){System.out.println("finalize called");}  
public static void main(String[] args){  
FinalizeExample f1=new FinalizeExample();  
FinalizeExample f2=new FinalizeExample();  
f1=null;  
f2=null;  
System.gc();  
}}  

在调用垃圾收集器之前。

The meaning of final in java is:
-applied to a variable means that the respective variable once initialized can no longer be modified

private final double numer = 12;

If you try to modify this value, you will get an error.

-applied to a method means that the respective method can't be override

 public final void displayMsg()
    {
        System.out.println("I'm in Base class - displayMsg()");
    }

But final method can be inherited because final keyword restricts the redefinition of the method.

-applied to a class means that the respective class can't be extended.

class Base
{

    public void displayMsg()
    {
        System.out.println("I'm in Base class - displayMsg()");
    }
}

The meaning of finally is :

class TestFinallyBlock{  
  public static void main(String args[]){  
  try{  
   int data=25/5;  
   System.out.println(data);  
  }  
  catch(NullPointerException e){System.out.println(e);}  
  finally{System.out.println("finally block is always executed");}  
  System.out.println("rest of the code...");  
  }  
} 

in this exemple even if the try-catch is executed or not, what is inside of finally will always be executed.
The meaning of finalize:

class FinalizeExample{  
public void finalize(){System.out.println("finalize called");}  
public static void main(String[] args){  
FinalizeExample f1=new FinalizeExample();  
FinalizeExample f2=new FinalizeExample();  
f1=null;  
f2=null;  
System.gc();  
}}  

before calling the Garbage Collector.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文