美文网首页
final 关键字

final 关键字

作者: Aluha_f289 | 来源:发表于2018-04-03 21:13 被阅读0次

final 关键字用于限定用户修改变量或者重写一个类还有方法。
final关键字的作用
1.禁止止变量的值被改变
2.禁止方法被重写
3.禁止一个类被继承。
实例1.禁止变量被改变

class Bike9 {
    final int speedlimit = 90;// final variable

    void run() {
        speedlimit = 400; // 不可以修改 final 变量的值
    }

    public static void main(String args[]) {
        Bike9 obj = new Bike9();
        obj.run();
    }
}

以上运行报错

[编译错误]Compile Time Error

实例2禁止方法被重写

class Bike {
    final void run() {
        System.out.println("running");
    }
}

class Honda extends Bike {
    void run() { // final方法,不可以重写
        System.out.println("running safely with 100kmph");
    }

    public static void main(String args[]) {
        Honda honda = new Honda();
        honda.run();
    }
}

运行

[编译错误]Compile Time Error

3.禁止一个类被继承

final class Bike {
}

class Honda1 extends Bike { // 不可以扩展 final 类
    void run() {
        System.out.println("running safely with 100kmph");
    }

    public static void main(String args[]) {
        Honda1 honda = new Honda();
        honda.run();
    }
}

运行

[编译错误]Compile Time Error
···
最后fianl修饰一个方法时,是否可以被继承
答案是可以被继承的,但是不能被重写。

相关文章

网友评论

      本文标题:final 关键字

      本文链接:https://www.haomeiwen.com/subject/luachftx.html