final修饰特点
1.修饰类,类不能被继承,相当于没有子类
2.修饰变量,变量就变成了常量,只能被赋值一次
3.修饰方法,方法不能被重写
public class Demo03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//2.修饰变量,变量就成了常量,只能被赋值一次
//The final local variable a cannot be assigned.
//局部变量不能再被赋值了
final int a = 12;
//a = 11;
System.out.println(a);
}
}
//1.修饰类,类不能被继承
//final class Father
class Father{
public void drive(){
System.out.println("开法拉第。。。");
}
//3.方法sing不能被重写
final void sing(){
System.out.println("父亲唱歌");
}
}
//The type Son cannot subclass the final class Father
//Son 不能成为final Father的子类
class Son extends Father{
}
final修饰局部变量特性
1.修饰基本类型,值不能被改变
2.修饰引用类型,地址值不能被改变,对象中的属性可以改变
3.修饰引用类型不可用再New
public class Demo04 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//修饰基本类型则a不能再被赋值
final int a = 10;
//a = 11;
//2.修饰引用类型
final Sat cat = new Sat("大黄",4);
//cat = new Sat("大红",4);
cat.say();
}
}
class Sat{
String name;
int legs;
public Sat(String name, int legs) {
super();
this.name = name;
this.legs = legs;
}
public void say(){
System.out.println("我是" + name + ",我有" + legs + "条腿。");
}
}
final修饰变量叫做常量,一般与public static共用
非静态final修饰变量的两个初始化时机
1.定义变量的时候直接初始化【常用】
2.在构造方法中初始化
个人笔记,写的比较混乱,勿怪。