Java-final关键字

final:最终的,到此为止

分三种情况:

1、修饰类

表示该类不能被继承和扩展

final class A {}

class B extends A {}// 编译器报错,表示无法继承

2、修饰方法

子类无法覆盖和重写该方法

class A {
    final void method() {}
}

class B extends A {
    @override
    void method() {}// 编译器报错,无法重写该方法
}

3、修饰变量

对对象来说,保证变量的引用不变,其值可以被修改

对基本类型数据时,保证值不变。修饰方法参数时也是一样

public class FinalDemo {

    public static void main(String[] args) {
        String a = "Hello2";
        final String b = "Hello";
        String c = b + 2;
        System.out.println(a.equals(c));
        String d = "Hello";
        String e = d + 2;
        System.out.println(a.equals(e));
        
        // 修改当前对象的数值
        final StringBuffer tempbuffer = new StringBuffer("Hello, world!");
        tempbuffer.append("This is final string!");
        
//        tempbuffer = new StringBuffer();// 无法重新引用新的数据
    }

}

 

posted @ 2018-02-27 16:28  缇布  阅读(119)  评论(0编辑  收藏  举报