• final


    一:空白final

    理解:在类里面进行final值的初始化不赋值,在类的构造方法中赋值。

    优点:可以根据对象不同,值不同,但是又保证对象恒定不变的特效。

    代码:

     1 public class ewq2 {  
     2   
     3     final private int a;  
     4   
     5     public ewq2(int x) {  
     6         a = x;  
     7         // a++;  错误 a并不能改变  
     8   
     9     }  
    10   
    11     public int toInteger() {  
    12   
    13         return a;  
    14   
    15     }  
    16   
    17     public static void main(String[] args) {  
    18   
    19         ewq2 w = new ewq2(3);  
    20   
    21         System.out.println("number-->" + w.toInteger());  
    22   
    23         System.out.println("
    ---------");  
    24         ewq2 w2 = new ewq2(10);  
    25   
    26         System.out.println("number-->" + w2.toInteger());  
    27   
    28     }  
    29   
    30 } 

    二:使用final指定参数

    理解:

    ①基本类型:不能被修改,不能被重新赋值

    ②引用类型:引用的对象不能改变,对象可以改变

    特性:你可以读参数,但是无法修改参数

    代码:

     1 class BB  
     2 {  
     3     public int i;     
     4 }  
     5 class PP  
     6 {  
     7     public static void f(final BB ref) // ref不能修改(程序传递的是引用,也就是地址,所以你的地址不能修改)  
     8     {  
     9         ref.i = 55;  
    10     }  
    11     public static void main(String args[])  
    12     {  
    13         BB x = new BB();  
    14         f(x);  
    15         System.out.println(x.i);  // i可以修改  
    16     }  
    17 }  

    三:使用final修饰方法

    理解:当该方法不想被覆盖或者重写时,使用

    优点:把方法锁定,以防任何继承类修改他的含义

    代码:

     1 public class A {
     2 
     3     // final方法f
     4 
     5     public final void f() {
     6 
     7        System.out.println("类A中的final方法f被调用了");
     8 
     9     }
    10 
    11 }
    12 
    13 public class B extends A {
    14 
    15     // 编译错误!父类的f方法是final类型,不可重写!
    16 
    17     //! public void f() {
    18 
    19     //!     System.out.println("类B中的方法f被调用了");
    20 
    21     //! }
    22 
    23 }

     三:使用final修饰类

    理解:不希望某个类有子类

    注意点:final类的方法默认是final的不能继承

  • 相关阅读:
    强制类型转换问题
    Linux学习1
    Android图像处理2
    Android图像处理1
    java环境搭建的问题
    Perl中的正则表达
    HTML中href的链接刷新页面问题
    ajax中的post方法中回调函数不执行的问题
    Tomcat 类加载器打破双亲委派模型
    电商支付的自动化测试选型之路
  • 原文地址:https://www.cnblogs.com/jiuhaoyun/p/9140299.html
Copyright © 2020-2023  润新知