java笔记--day09--final关键字

  • 1 final:adj. 最终的;决定性的;不可更改的
  • 2 final关键字可以修饰类、成员变量、成员方法
    • final关键字修饰类,该类不能被继承
    • final关键字修饰变量,该变量就变成了常量,只能被赋值一次
    • final关键字修饰方法,该方法不能被重写(override)
  • 3 final关键字注意事项
    • 3.1 修饰基本数据类型
      • 代码Demo如下
            class StudentDemo{
    public static void main(String[] args) {
        int num1 = 10;
        final int num2 = 20;
        System.out.println("num1 is "+num1);
        System.out.println("num2 is "+num2);
        System.out.println();

        num1 = 100;
        //num2 = 200;//如果修改num2,编译会出错,通不过
        System.out.println("num1 is "+num1);
        System.out.println("num2 is "+num2);
    }
}
        运行结果:
        num1 is 10
        num2 is 20

        num1 is 100
        num2 is 20

可以看出,final修饰的基本数据类型,该变量是不能再改变的了

  • 3.1 修饰引用数据类型
    代码Demo如下:
错误代码:
class Student{
    int age = 10;
    final int age2 = 28; //can not be changed
    public Student(){}

    public void show(){
        System.out.println("Age is "+ age);     
    }
}
class FinalDemo3{
    public static void main(String[] args) {
        final Student s1 = new Student();
        s1.age = 11;
        s1.show();

        Student s2 = new Student();
        s2.age = 12;
        s2.show();

        s1 = s2;    //this line must be commented out.
    }
}
运行结果:
FinalDemo3.java:20: 错误: 无法为最终变量s1分配值
                s1 = s2;        //this line must be commented out.
                ^
1 个错误



正确代码:
class Student{
    int age = 10;
    final int age2 = 28; //can not be changed
    public Student(){}

    public void show(){
        System.out.println("Age is "+ age);     
    }
}
class FinalDemo3{
    public static void main(String[] args) {
        final Student s1 = new Student();
        s1.age = 11;
        s1.show();

        Student s2 = new Student();
        s2.age = 12;
        s2.show();

        //s1 = s2;  //this line must be commented out.
    }
}
运行结果:
Age is 11
Age is 12

可以看出,final修饰引用数据类型(代码中的s1)时。不能改变的是其地址值(所以s1 = s2;这句话是错误的),但是其地址值所指向的数据是可以改变的(s1.age = 11;)。

  • 4 final修饰变量的初始化时机
    对3中的class Student进行反编译:
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 
// Source File Name:   FinalDemo3.java

import java.io.PrintStream;

class Student
{

    int age;
    final int age2 = 28;

    public Student()
    {
        age = 10;
    }

    public void show()
    {
        System.out.println((new StringBuilder()).append("Age is ").append(age).toString());
    }
}

可以看出,final修饰的变量是在对象构造完成之前进行的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值