如何在Java中使用final关键字?
final修饰符用于将类标记为final,使其无法继承,以防止重写方法,并防止更改变量的值。如果声明为finalis,则方法的参数也不能在方法中修改。
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 {
}
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短