final 修饰符
1. 应用范围
final 修饰符应该使用在类、变量以及方法上
2. final 修饰类
Note that you can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.注意,你也可以声明整个类的 final 。 声明为 final 的类不能被子类化。 例如,当创建不可变类(如String类)时,这特别有用。
如果一个类被final 修饰,表示这个类是最终的类,因此这个类不能够在被继承,因为继承就是对类进行扩展。
示例
package com . we . inheritance . _final ;//final 修饰的类不能够被继承public final class FinalClass {public void show (){System . out . println ( " 这是最终类里面的方法 " );}}package com .we . inheritance . _final ;// 这里会报编译错误,因此 FinalClass 不能够被继承public class ChildClass extends FinalClass { }
3. final 修饰方法
You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final.你可以将类的某些或所有方法声明为 final 。 在方法声明中使用 final 关键字表示该方法不能被子类覆盖。 Object 类就是这样做的 - 它的许多方法都是最终的。
示例
package com . we . inheritance . _final ;public class FinalMethod {public final void show (){System . out . println ( " 这是一个最终方法,不能被重写 " );}}package com .we . inheritance . _final ;public class ChildMethod extends FinalMethod {//这里也会报编译错误,因为父类中的 show() 方法时最终的,不可被重写public void show (){}}
4. final 修饰变量
final 修饰变量的时候,变量必须在对象构建时完成初始化。 final 修饰的变量称为常量。
示例
package com .we . inheritance . _final ;public class FinalVariable {//final修饰的变量一定要在对象创建时完成赋值操作, final 修饰的变量称之为常量,不可被更改private final int number ;//static final修饰的变量就是静态常量public static final String COUNTRY = " 中国 " ;public FinalVariable (){this . number = 10 ;}public void change (){// this.number = 11; //因为 number 是一个常量,不能再被更改,因此会报编译错误}}
思考如下代码的执行过程:
package com .we . inheritance . test ;public class Father {static {System . out . println ( " 父类静态代码块执行 " );}public Father (){super ();System . out . println ( " 父类构造方法执行 " );}}
package com .we . inheritance . test ;public class Child extends Father {static {System . out . println ( " 子类静态代码块执行 " );}public Child (){super ();System . out . println ( " 子类构造方法执行 " );}}
package com .we . inheritance . test ;public class Test {public static void main ( String [] args ) {new Child ();//构建Child 对象时,发现 Child 是 Father 的子类,而 Father 又是 Object 的子类。因此 JVM会首先加载 Object 类//然后再加载Father 类,最后再加载 Child 类。而静态代码块是在类第一次加载时执行,而且只会执行一次。因此//Father类中的静态代码块先执行,然后再执行Child 类中的静态代码块。然后才执行 newChild();代码。//父类静态代码块执行//子类静态代码块执行//父类构造方法执行//子类构造方法执行}}