package com.qfedu.f_final;/*
final关键字可以修饰
局部变量 有且只能被赋值一次,赋值之后不可以修改
成员变量 定义时必须初始化,未初始化报错
成员方法 使用final修饰的方法为最终方法,不能被重写!!!
类 没有子类,不能被继承
Java中是存在一些类是使用final修饰的
String类
*/finalclassFather{finalpublicvoidgame(){
System.out.println("黄金矿工!!!");}}// The type Son cannot subclass the final class Father// Son类不能是final修饰的类Father类的子类,不能继承Father// 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.f_final;classDog{
String name;int age;}publicclassDemo2{publicstaticvoidmain(String[] args){
Dog dog =newDog();
dog.name ="八公";
dog.age =15;/*
* final修饰的是dog1,dog1是一个类对象,同时是一个引用数据类型的变量。
* dog1存储数据不可以改变!!!dog1指向不可以改变,但是dog1指向空间
* 中的内容可以改变。
*
* dog1看作你你的房产证,房产证上面的地址是不可以改变的!!!
* 但是房子装修和房产证有关吗?
*/final Dog dog1 =newDog();// dog1能不能操作成员变量???
dog1.name ="骚杰";
dog1.age =16;// 能不能修改???
dog1.name ="一杯二锅头";
dog1.age =20;
Dog dog2 = dog1;
dog2 =newDog();// The final local variable dog1 cannot be assigned. // It must be blank and not using a compound assignment// dog1 = new Dog();}}