Chinaunix首页 | 论坛 | 博客
  • 博客访问: 89555
  • 博文数量: 19
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 158
  • 用 户 组: 普通用户
  • 注册时间: 2015-12-16 20:28
个人简介

Stay Hungry, Stay Foolish

文章分类

全部博文(19)

文章存档

2016年(9)

2015年(10)

我的朋友

分类: Java

2015-12-17 20:43:54

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

1.修饰类

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



  1. package com.qunar.bean;
  2. public final class Student {
  3.     
  4. }


  1. package com.qunar.bean;
  2. // Remove final modifier from Student
  3. public class Qunar extends Student{
  4.     public static void main(String[] args){
  5.         
  6.     }
  7. }

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

2.修饰方法

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

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

注:类的private方法会隐式地被指定为final方法。


  1. package com.qunar.bean;
  2.  
  3. public class Student {
  4.  private String name;
  5.  private int age;
  6.  private String sex;
  7.  
  8.  public final void play(){
  9.  System.out.println("Student");
  10.  }
  11. }

  1. package com.qunar.bean;
  2. public class Qunar extends Student{
  3.     // Remove final modifier from Student.play
  4.     public void play(){
  5.         System.out.println("Qunar");
  6.     }
  7.     public static void main(String[] args){
  8.         Qunar qunar = new Qunar();
  9.         qunar.play();
  10.     }
  11. }

3.修饰属性

final修饰属性则该类的属性不会隐式的初始化(类的初始化属性必须有值)或在构造方法中赋值(但只能选其一)}

  1. package com.qunar.bean;
  2. public class Student {
  3.     private String name;
  4.     // 报错 final filed age may not hava been initialized
  5.     // final private int age;
  6.     final private int age = 10;
  7.     private String sex;
  8.     
  9.     public final void play(){
  10.         // final filed Student.age cannot been assigned
  11.         // age = 30;
  12.         System.out.println("Student");
  13.     }
  14. }

4.修饰变量

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








阅读(1290) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~