Think in java笔记 final

来源:互联网 发布:网络卖电影挣钱 编辑:程序博客网 时间:2024/05/17 07:29

Think in java笔记 final

Many programming languages have a way to tell the compiler that a piece of data is “constant.” A constant is useful for two reasons:
1. It can be a compile-time constant that won’t ever change.
2. It can be a value initialized at run time that you don’t want changed.

很多语言都有一定的方法告诉编译器,一块数据是常量,使用常量(final)的原因有两个:
1. 可以是一个编译的常量,这样子有些计算就可以直接在编译阶段完成。
2. 可以是一个不可以改变的常量。

在用于基本类型和对象类型是不同的效果:
1. 基本类型必须一般要在定义时赋值,否则会报编译错误。这里的作用主要是为了避免以后程序的异常。这里有一种异常情况:

Java allows the creation of blank finals, which are fields that are declared as final but are not
given an initialization value. In all cases, the blank final must be initialized before it is used,
and the compiler ensures this. However, blank finals provide much more flexibility in the use
of the final keyword since, for example, a final field inside a class can now be different for
each object, and yet it retains its immutable quality.
Java允许创建空白final(即未定义的final变量),空白final提供了在使用的时候很大的灵活性,但是这种情况下编译器会在使用前检查,通常的做法就是:空白final,编译器赋值。

  1. 对象类型只是强调引用不能变,就是存在栈中的引用,而不是引用的对象不能变化。
0 0