修饰类
public final class Test ( ) { }
修饰方法
public final void test ( ) { }
不能被子类覆盖重写 可以有子类 不能与abstract一起使用,互相矛盾
修饰局部变量
局部变量不能更改,一次赋值,终生不变 基本类型:数据不可变 引用类型:地址值不可改变
public class Test2 {
private String name;
public Test2 ( String name) {
this . name = name;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public static void main ( String[ ] args) {
final Test2 test2 = new Test2 ( "abc" ) ;
System. out. println ( test2. getName ( ) ) ;
test2. setName ( "def" ) ;
System. out. println ( test2. getName ( ) ) ;
}
}
修饰成员变量
成员变量有默认值,使用final 必须进行手动赋值 直接赋值,构造方法赋值(2选1)
public class Test2 {
private final String name = "abc" ;
public Test2 ( String name) {
this . name = name;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
}
public class Test2 {
private final String name;
public Test2 ( ) {
name = "" ;
}
public Test2 ( String name) {
this . name = name;
}
public String getName ( ) {
return name;
}
}