package com.qfedu.e_final;/*
final关键字可以修饰
局部变量 有且只能被赋值一次, 赋值之后不能修改
成员变量 定义时必须初始化, 未初始化报错
成员方法 使用final修饰的方法为最终方法, 不能被重写
类 没有子类 不能被继承
*/finalclassFather{finalpublicvoidgame(){
System.out.println("黄金矿工");}}// The type Son cannot subclass the final class Father// Son类不能是final修饰的类Father类的子类, 不能继承Fahter// class Son extends Father {// The blank final field age may not have been initialized// 使用final修饰的成员变量还没有被初始化// final int age = 10;// Cannot override the final method from Father// 使用final修饰的方法为最终方法, 不能被重写// public void game() {// System.out.println("Pubg");// }// }publicclassDemo1{publicstaticvoidmain(String[] args){finalint num;
num =10;// The final local variable num may already have been assigned// 使用final修饰的局部变量num已经被赋值// num = 20;}}
7.2 思考题
package com.qfedu.e_final;classDog{
String name;int age;}publicclassDemo2{publicstaticvoidmain(String[] args){
Dog dog =newDog();
dog.name ="八公";
dog.age =15;/*
* final 修饰的是dog1, dog1是一个类对象, 同时是一个引用数据类型的变量
* dog1存储数据不可以改变!! dog1只想不可以改变, 但是dog1指向空间中的内容可以改变
*/final Dog dog1 =newDog();// dog1 能不能操作成员变量?
dog1.name ="骚杰";
dog1.age =16;// 能不能修改??
dog1.name ="123";
dog1.age =20;// The final local variable dog1 cannot be assigned. // It must be blank and not using a compound assignment// dog1 = new Dog();}}