1, final overview
-
be used to modify the final keyword class, method and variable, the modified final class can not be inherited;
-
The final modification method can not be overwritten;
-
final modified variables can not be changed.
-
final: final.
2, final modification features
-
Modified class, the class can not be inherited
-
Modifying a variable, it becomes a constant, it can only be assigned once
-
Modification methods, the method can not be overridden
class Demo1_Final {
public static void main(String[] args) {
Son s = new Son();
s.print();
}
}
/*final class Father {
public void print() {
System.out.println("访问底层数据资源");
}
}*/
class Son /*extends Father*/ {
final int NUM = 10;
//常量命名规范,如果是一个单词,所有字母大写,如果是多个单词,每个单词都大写,中间用下划线隔开
public static final double PI = 3.14;
//final修饰变量叫做常量,一般会与public static共用
public void print() {
//NUM = 20;
System.out.println(NUM);
}
}
3, final local variables modified keywords
[2] base type, the value can not be changed
[3] reference type, the address value can not be changed, object properties may be varied
class Demo2_Final {
public static void main(String[] args) {
final int num = 10;
//num = 20;
System.out.println(num);
final Person p = new Person("张三",23);
//p = new Person("李四",24);
p.setName("李四");
p.setAge(24);
System.out.println(p.getName() + "..." + p.getAge());
method(10);
method(20);
}
public static void method(final int x) {
System.out.println(x);
}
}
class Person {
private String name; //姓名
private int age; //年龄
public Person(){} //空参构造
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public void setName(String name) { //设置姓名
this.name = name;
}
public String getName() { //获取姓名
return name;
}
public void setAge(int age) { //设置年龄
this.age = age;
}
public int getAge() { //获取年龄
return age;
}
}
4, final modification of the timing of initialization of variables)
-
Display initialization
-
Before he can object construction is completed
class Demo3_Final {
public static void main(String[] args) {
Demo d = new Demo();
d.print();
}
}
/*
* A:final修饰变量的初始化时机
* 显示初始化
* 在对象构造完毕前即可
*/
class Demo {
final int num; //成员变量的默认初始化值是无效值
public Demo() {
num = 10;
}
public void print() {
System.out.println(num);
}
}