Java 笔记分享 —— final 关键字

目录

1.1 前言

1.2 最终变量

1.3 最终类

1.4 最终方法

1.5 最终参数

1.6 总结


1.1 前言

final 即为最终关键字,被它修饰即不能再更改。final 可以修饰变量,类,方法甚至是参数,但是不能修饰构造函数。

1.2 最终变量

最终变量一旦被赋值就不能再更改。初始化方法有以下几种:

  • 直接用等号初始化;
public class test {
    public static void main(String args[]) {
        // 等号直接赋值最终变量
        final int finalVariate = 1;
        System.out.println(finalVariate);
    }
}
运行结果:
    1
  • 在构造函数中初始化;
public class test {
    final int finalVariate;

    /*
    默认构造函数初始化最终变量
     */
    test() {
        finalVariate = 1;
    }

    public static void main(String args[]) {
        test1 t = new test1();
        System.out.println(t.finalVariate);
    }
}
运行结果:
    1
  • 在静态块中初始化:只适用于静态最终变量的初始化;
public class test {
    static final int finalVariate;

    /*
    静态块初始化最终空白变量
     */
    static {
        finalVariate = 1;
    }

    public static void main(String args[]) {
        // 由于是被 static 可直接调用
        System.out.println(finalVariate);
    }
}
运行结果:
    1

1.3 最终类

最终类不能被继承。

/*
* 最终父类
 */
final class Parent {
    void method() {
        System.out.println("Parent");
    }
}

/*
* 继承父类的子类,因为父类被 final 修饰,继承的话会报错
 */
class Son extends Parent {
    void method() {
        System.out.println("Son");
    }
}

public class test1 {
    public static void main(String args[]) {
        Son testClass = new Son();
        testClass.method();
    }
}
运行结果:(报错)
    无法从最终test1.Parent进行继承

1.4 最终方法

最终方法不能被覆盖。

​
/*
* 父类
 */
class Parent {
    final void finalMethod() {
        System.out.println("Parent");
    }
}

/*
* 继承父类的子类
 */
class Son extends Parent {
    /*
    最终方法不能被覆盖,这里是错误的
     */
    void finalMethod() {
        System.out.println("Son");
    }
}

public class test {
    public static void main(String args[]) {
        Son testClass = new Son();
        testClass.finalMethod();
    }
}

​
运行结果:(报错)
    test.Son中的finalMethod()无法覆盖test1.Parent中的finalMethod()被覆盖的方法为final

1.5 最终参数

最终参数不能被更改。

public class test {

    /*
    测试最终参数的方法
     */
    int testArgument(final int n) {
        // 这里错误的,修改方法就是将 n * n 去掉
        n = n * n;
        return n;
    }

    public static void main(String args[]) {
        test t = new test();
        int receiveArgument = t.testArgument(2);
    }
}
运行结果:(报错)
    不能分配最终参数n

1.6 总结

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值