JAVA菜鸟入门(8) Java的Final关键字

本文详细解析了Java中final关键字的多种用途,包括final变量、final方法、final类及final参数的应用场景与注意事项,并提供了丰富的示例代码。

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

java final 和C++的const功能类似,用来表达常量,还能用在class或者method上,提供不同的用法。

1. Java Final Variable 

Once a final variable has been assigned, it always contains the same value.但是 static final和private final是有区别的。
这个区别一般体现在类中,在类中,被写为private static final v.s. private final.

(1).什么情况下用private static final,什么情况下用 private final

如果你有一个类,它的instance不管运行多少次,你的意图是它的variable不变化
你那么就该用private static final

如果你有一个类,在它的instance每次运行的生命周期中,你的意图是它的variable不变化
你那么就该用private final


(2).如何用private static final
第一种 正确
class A {
     private static final int x;
     static {
          x = 5;
     }
}


第二种正确
class A {
     private static final int x = 5;
...
}


(3). 如何用private final
第一种 正确
class A {
     private final int x;
     public A() {
          x = 5;
     }
}

第二种 正确
class A {
     private final int x = 5;
    ...
}


(4) 如果final中存的不是primitive type,是instance of a class, 那么。
If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object(e.g. add an item, delete an item, depending on whether the object is mutable or not), but the variable will always refer to the same object


2. final method
If you make any method as final, you cannot override it.
class Bike{
    final void run(){
        System.out.println("running");
    }
}
class Honda extends Bike{
    //Output:Compile Time Error
    void run(){System.out.println("running safely with 100kmph");} 
    public static void main(String args[]){
        Honda honda= new Honda();
        honda.run();
    }
}



3. final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
//:Compile Time Error
class Honda1 extends Bike{
    void run(){System.out.println("running safely with 100kmph");}
    public static void main(String args[]){
    Honda1 honda= new Honda();
    honda.run();
    }
}



4. final parameter
If you declare any parameter as final, you cannot change the value of it.
class Bike11{
     int cube(final int n){
     n=n+2;//can't be changed as n is final
     n*n*n;
}
public static void main(String args[]){
     Bike11 b=new Bike11();
     b.cube(5);
     }
}


5. 如果要在inner class中使用外层class的变量
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change.
import javax.swing.*;
public class FooGUI {
    public static void main(String[] args) {
        //initialize GUI components
        final JFrame jf = new JFrame("Hello world!"); //allows jf to be accessed from inner class body
        jf.add(new JButton("Click me"));
 

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                jf.pack(); //this would be a compile-time error if jf were not final
                jf.setLocationRelativeTo(null);
                jf.setVisible(true);
            }
        });
    }
}
 


参考资料:
1 http://www.javatpoint.com/final-keyword
2 http://stackoverflow.com/questions/5093744/initialize-a-static-final-field-in-the-constructor
3 http://en.wikipedia.org/wiki/Final_(Java)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值