4. final

定义

修饰类:表示类不可变,不可继承,比如String,不可变性

修饰方法: 表示改方法不可重写,比如模板方法,可以固定我们的算法,参数 可以改变,但其过程不可改变

修饰变量:这个变量就是常量

注意

修饰的是基本数据类型,这个值本身不能修改

final int a=5;
a=7;   //修饰常量不能改变其值(会报错)
System.out.println(a);

修饰的是引用类型,引用的指向不能修改,但是内容可以改变

import java.util.Objects;

public class Main {
    
    
    public static void main(String[] args) {
    
    

        final Student st=new Student("xsj", 18);
        //这样是可以的
        st.setAge(20); 
        //这样不可以,报错,new 改变了引用的指向
        st=new Student("x",19); 
    }
}

class Student {
    
    
    String name;
    int age;


    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/115336503