[Java开发之路](1)final关键字

在Java中,final关键字可以用来修饰类、方法和变量(包括成员变量和局部变量)。下面就从这三个方面来了解一下final关键字的基本用法。

1.修饰类

final修饰类时,则该类不能被继承

    
    
    
    
package com.qunar.bean;
 
public final class Student {
}
     
     
     
     
package com.qunar.bean;
 
// Remove final modifier from Student
public class Qunar extends Student{
 
public static void main(String[] args){
}
}


在使用final修饰类的时候,要注意谨慎选择,除非这个类真的在以后不会用来继承或者出于安全的考虑,尽量不要将类设计为final类。

2.修饰方法

final修饰方法,则该方法不允许被覆盖(重写)
使用final方法的原因有两个:第一个原因是把方法锁定,以防任何继承类修改它的含义;第二个原因是效率,在早期的Java实现版本中,会将final方法转为内嵌调用,但是如果方法过于庞大,可能看不到内嵌调用带来的任何性能提升。在最近的Java版本中,不需要使用final方法进行这些优化了。

如果只有在想明确禁止该方法在子类中被覆盖的情况下才将方法设置为final的。

注:类的private方法会隐式地被指定为final方法。
    
    
    
    
package com.qunar.bean;
 
public class Student {
private String name;
private int age;
private String sex;
public final void play(){
System.out.println("Student");
}
}

    
    
    
    
package com.qunar.bean;
 
public class Qunar extends Student{
// Remove final modifier from Student.play
public void play(){
System.out.println("Qunar");
}
public static void main(String[] args){
Qunar qunar = new Qunar();
qunar.play();
}
}

3.修饰属性

final修饰属性则该类的属性不会隐式的初始化(类的初始化属性必须有值)或在构造方法中赋值(但只能选其一)
    
    
    
    
package com.qunar.bean;
 
public class Student {
private String name;
// 报错 final filed age may not hava been initialized
// final private int age;
final private int age = 10;
private String sex;
public final void play(){
// final filed Student.age cannot been assigned
// age = 30;
System.out.println("Student");
}
}


4.修饰变量

final修饰变量则该变量的值只能赋一次值,即变为常量








你可能感兴趣的:(java,final)