Final变量的含义

许多语言都有“固定不变的存储区”的概念,在C++中用CONST表示,在java中则用final表示,当fianl用于修饰一个变量时,不管该变量是一个类的成员还是一个临时的变量这个变量都不能重新被赋值。

例如下面的代码

package Stephen.Class.chapter7;
//final修饰符的应用
public class Cow {
    public static final String SKIN_COLOR = "浅黄色";
    public static final String CHARACTOR = "温顺的";        //性格
    public void eat(){
        System.out.println("牛正在吃草");
    }
    public static void main(String[] args){
        Cow cow = new Cow();
        cow.eat();
        //cow.SKIN_COLOR = "深黄色的";这样在改变牛的颜色是不正确的,因为SKIN_COLOR是final变量
        System.out.println(cow.SKIN_COLOR);
        System.out.println(cow.CHARACTOR);
    }
}

运行结果为

原文地址:https://www.cnblogs.com/lidaojian/p/2560287.html