阿里云【名师课堂】Java面向对象开发63:final关键字
具体内容
final被称为终结器,可以被用来定义类、方法、属性。
1、使用final定义的类不能有子类
final class Person {}
class Student extends Person {}
public class TestDemo {
public static void main(String args[]) {
}
}
2、使用final定义的方法不能被子类所覆写
class Person {
public final void method() {}
}
class Student extends Person {
public void method() {}
}
public class TestDemo {
public static void main(String args[]) {
}
}
3、使用final定义的变量就成为了常量
常量必须在声明时赋值,且不允许更改
class Person {
public final int SCORE = 100 ; // 代码规范:常量标识符全大写
public void method() {
SCORE = 110 ;
}
}
public class TestDemo {
public static void main(String args[]) {
}
}
在开发过程中如果要定义常量,往往使用static
会定义全局常量:public static final int SCORE = 100 ;