final关键字
final关键字的用法:
1. final关键字修饰一个基本类型的变量时,该变量不能重新赋值,第一次的值为最终的。
class Main
{
public static void main(String[] args)
{
int n = 1;
final int m = 2;
m = n; //Cannot assign a value to final variable
}
}
- fianl关键字修饰一个引用类型变量时,该变量不能重新指向新的对象。
class Main
{
public static void main(String[] args)
{
String str1 = "chenjipayne";
final String str2 = "Hellow World";
str2 = str1; //Cannot assign a value to final variable
}
}
- final关键字修饰一个函数的时候,该函数不能被重写。
class Animal{
String name;
String color;
public Animal(String name,String color){
this.name = name;
this.color = color;
}
public void eat(){
System.out.println(name+"eat");
}
public final void run(){
System.out.println(name+"run");
};
}
class Dog extends Animal{
public Dog(String name,String color){
super(name,color);
}
public void run(){//cannot override 'run()' ; overridden method is final
System.out.println(name+" dog is running");
}
}
- final关键字修饰一个类的时候,该类不能被继承。
final class Animal{
String name;
String color;
}
class Dog extends Animal{
//Cannot inherit from final 'Animal'
}
常量 的修饰符一般为: public static final
class Circle{
double r;
public static final double pi = 3.14; //将π定义为常量
public Circle(double r){
this.r = r;
}
//计算面积
public final void getArea(){
System.out.println("圆形的面积是:"+r*r*pi);
}
}