java final说明,举例代码
时间: 2024-09-13 13:04:21 浏览: 47
Java中的`final`关键字是一个非常重要的修饰符,它被用来声明属性、方法和类,以指示它们在某种意义上是“最终”的。这个修饰符的使用意味着它们不能被继承或修改。具体来说,`final`关键字在不同上下文中的作用如下:
1. 当用在类上时,表示该类不能被继承。
2. 当用在方法上时,表示该方法不能被子类重写。
3. 当用在变量上时,表示变量一旦被赋值之后,其值就不可更改。
下面是一些`final`关键字的使用示例:
```java
final class FinalClass { // 不能被继承
}
class Parent {
final void display() { // 不能被重写
System.out.println("Parent display method.");
}
}
public class FinalDemo {
public static void main(String[] args) {
final int x = 10; // x是一个final变量,一旦被赋值后不可更改
// x = 20; // 错误: 无法为最终变量x分配值
Parent p = new Parent();
p.display(); // 输出: Parent display method.
// p.display = new Parent()::display; // 错误: display方法是final的,不能被覆盖
}
}
```
在上述代码中,`FinalClass`类不能被其他类继承;`display`方法在`Parent`类中声明为`final`,因此它不能被`Parent`类的任何子类所重写;`x`变量被声明为`final`,这意味着一旦对它赋值后,它的值就不能被改变。
阅读全文
相关推荐


















