final修饰的对象可以看做是常量,不可以被重新赋值或者修改
-
使用final关键字修饰的变量只能被赋值一次
-
在成员方法中被final修饰的变量可以先不赋值,在后面只能被赋值一次
void sing(){ final int b; //final修饰 b = 8; //只能被赋值一次 b = 10;//不能被赋值,程序报错 System.out.println("我在唱歌"); } -
在类中被final修饰的变量也就是成员变量必须在定义时赋值,否则程序会报错
public class Persons { //final int sing; //未赋初始值程序报错 final int sing = 5;//必须赋初始值 void sing(){ final int b; //final修饰 b = 8; //只能被赋值一次 b = 10;//不能被赋值,程序报错 System.out.println("我在唱歌"); } }
-
-
使用final关键字修饰的类不能被继承
首先创建一个人类和一个学生类
public class Person { //创建一个人类 String name; //设定名字 int age; //设定年龄 void say(){ //说话的方法 System.out.println("我的名字是:"+name+"我的年龄是"+age); } } public class Students extends Person{ //继承于人类 void write(){ System.out.println("我在写作业"); } }如上的程序是正确的,但是如果用final来修饰类,则不可以被继承
public final class Person { //创建一个人类 String name; //设定名字 int age; //设定年龄 void say(){ //说话的方法 System.out.println("我的名字是:"+name+"我的年龄是"+age); } } public class Students extends Person{ //继承于人类,程序报错,Person被final修饰 void write(){ System.out.println("我在写作业"); } } -
使用final关键字修饰的方法不能被重写
如果使用final修饰方法,那此方法就不能被重写
public final class Person { //创建一个人类 String name; //设定名字 int age; //设定年龄 void say(){ //说话的方法 System.out.println("我的名字是:"+name+"我的年龄是"+age); } } public class Students extends Person{ //继承于人类,程序报错,Person被final修饰 void say(){ System.out.println("我不能被重写,程序报错"); //程序报错 } }



