博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java中final关键字
阅读量:4467 次
发布时间:2019-06-08

本文共 1528 字,大约阅读时间需要 5 分钟。

在Java中,final关键字可以用来修饰类、方法和变量(包括成员变量和局部变量)。下面就从这三个方面来了解一下final关键字的基本用法。

1.修饰类

   当用final修饰一个类时,表明这个类不能被继承。final类中的成员变量可以根据需要设为final,final类中的所有成员方法都会被隐式地指定为final方法。

2.修饰方法

 final修饰的方法,方法不能被重写(可以重载多个final修饰的方法)。当父类中final修饰的方法同时访问控制权限为private,子类中不能直接继承到此方法,此时子类中定义相同的方法名和参数,为子类中重新定义了新的方法。

3.修饰变量

  1) final修饰变量表示常量,只能被赋值一次,赋值后值不再改变。如果final修饰一个引用类型时,值指的是地址的值,内容是可变的。

public class Test06 {    public static void main(String[] args){        Test06 test = new Test06();        final StringBuilder str = new StringBuilder("hello");        str.append("World");        System.out.println(str);            }}

  输出结果为helloWorld。

  2)当final变量是基本数据类型以及String类型时,如果在编译期间能知道它的确切值,则编译器会把它当做编译期常量使用。

  编译期间能知道它的确切值:

public class Test06 {    public static void main(String[] args)  {         String a = "helloworld";           final String b = "hello";         String d = "hello";         String c = b + "world";           String e = d + "world";         System.out.println((a == c));         System.out.println((a == e));     } }

  输出结果为true,false;编译器将其当成常量,a,c都指常量池中的"helloworld"。

 

  编译期间不知道它的确切值:

public class Test06 {    public static void main(String[] args)  {         String a = "helloworld";           final String b = getWord();         String d = "hello";         String c = b + "world";           String e = d + "world";         System.out.println((a == c));         System.out.println((a == e));     }     public static String getWord() {         return "hello";     } }

  输出结果为false,false。

转载于:https://www.cnblogs.com/1001n/p/8537100.html

你可能感兴趣的文章
The Most Simple Introduction to Hypothesis Testing
查看>>
UVA10791
查看>>
P2664 树上游戏
查看>>
jQuery 停止动画
查看>>
Sharepoint Solution Gallery Active Solution时激活按钮灰色不可用的解决方法
查看>>
教你50招提升ASP.NET性能(二十二):利用.NET 4.5异步结构
查看>>
lua连续随机数
查看>>
checkstyle使用介绍
查看>>
会了这十种Python优雅的写法,让你工作效率翻十倍,一人顶十人用!
查看>>
二维码图片生成
查看>>
在做操作系统实验的一些疑问
查看>>
Log4J日志配置详解
查看>>
NameNode 与 SecondaryNameNode 的工作机制
查看>>
Code obfuscation
查看>>
大厂资深面试官 带你破解Android高级面试
查看>>
node.js系列(实例):原生node.js实现接收前台post请求提交数据
查看>>
SignalR主动通知订阅者示例
查看>>
用python实现矩阵转置
查看>>
linux 小技巧(磁盘空间搜索)
查看>>
iOS开发——捕获崩溃信息
查看>>