final修饰符用于将类标记为final,使其无法继承,以防止重写方法,并防止更改变量的值。如果声明为final is,则方法的参数也不能在方法中修改。
package org.nhooo.example.fundamental;
public class FinalExample {
// 品种宣布为最终品种。
// 无法更改分配给繁殖的值
public final String breed = "pig";
private int count = 0;
// sound() method is declared final, so it can't be overridden
public final void sound() {
System.out.println("oink oink");
}
//number参数声明为final。
//不能改变分配给number的值
public int count(final int number) {
// 给数字变量赋值会导致
// 编译时错误
// number= 1;
count = +number;
return count;
}
public static void main(String[] args) {
FinalExample fe = new FinalExample();
// 为繁殖变量赋值会导致
// 编译时错误
//
//fe.breed= "dog";
int number = fe.count(20);
}
}
final class SubFinalExample extends FinalExample {
// try to override sound() method of superclass will cause a
// 编译时错误
//
// public void sound() {
// System.out.println(“ oink”);"oink");
// }
}
// 尝试继承一个声明为final的类将导致
// 编译时错误
//
class OtherFinalExample extends SubFinalExample {
}