zoukankan      html  css  js  c++  java
  • 高级类特性----final关键字

    final 关键字


    在Java中声明类、属性和方法时,可使用关键字final来修饰。

    final标记的变量(成员变量或局部变量)即成为常量,只能赋值一次

    final标记的类不能被继承。提高安全性,提高程序的可读性。

    final标记的方法不能被子类重写。增加安全性。

    final标记的成员变量必须在声明的同时或在每个构造方法中显式赋值,然后才能使用。final PI=3.14;


    关键字final应用举例


    public final class Test {
      public static int totalNumber= 5 ;
      public final int id;
      public Test() {
        id = ++totalNumber;//只能在构造方法中给final变量赋值
      }
      public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.id);
        final int i = 10;
        final int j;
        j = 20;
        j = 30; //非法
      }
    }


      

     1 public class TestFinal {
     2     
     3     int i = 10;
     4     int j;
     5     
     6     final int m = 10;
     7     final int n;
     8     
     9     public TestFinal() {
    10         n = 100;
    11     }
    12     
    13     public void test(){
    14         i = 10;
    15         j = 20;
    16         
    17 //        m = 100;
    18     }
    19     
    20     public static void main(String[] args) {
    22     }
    24 }
    25 
    26 final class A {
    27     
    28 }
    29 
    30 //class B extends A {
    31 //    
    32 //}
    33 
    34 class C {
    35     void method1(){}
    36 }
    37 
    38 class D extends C {
    39     @Override
    40     void method1() {
    41         // TODO Auto-generated method stub
    42         super.method1();
    43     }
    44 }
  • 相关阅读:
    前端博客收集
    Oracle 数据库性能调优
    vue解决跨域问题
    IIS相关问题及解决方案
    《软件测试工程师》学习笔记
    Matlab学习笔记(一)
    排序算法及分析
    Silverlight学习笔记——跨域调用
    Matlab学习笔记(三)
    C#的一些必备技术
  • 原文地址:https://www.cnblogs.com/justdoitba/p/7228235.html
Copyright © 2011-2022 走看看