zoukankan      html  css  js  c++  java
  • 定义常量的几种方式与调用

     1 .通过接口的形式

     1 interface ColorConstant {
     2      /**
     3       * 红色
     4       */
     5      int RED = 1;  
     6       /**
     7        * 黄色
     8       */
     9      int YELLOW = 2;
    10  }
    11 调用方式:ColorConstant.RED

    2.通过枚举类的形式(自定义的带有name,index属性的枚举类型必须要写构造函数)

     1 enum ConstantEnum {    
     2     RED("红色", 1), YELLOW("黄色", 2);
     3     private String name ;
     4     private int index ;  
     5     private Color( String name , int index ){
     6         this.name = name ;
     7         this.index = index ;
     8     }  
     9     public String getName() {
    10         return name;
    11     }
    12     public void setName(String name) {
    13         this.name = name;
    14     }
    15     public int getIndex() {
    16         return index;
    17     }
    18     public void setIndex(int index) {
    19         this.index = index;
    20     }
    21 }  
    22 调用方式:ConstantEnum.RED.getName();
    23 //遍历所有的枚举
    24         for( ConstantEnum color : ConstantEnum .values()){
    25             System.out.println( color + "  name: " + color.getName() + "  index: " + color.getIndex() );
    26         }

    3.使用类的形式

    1 class ColorConstant {    
    2     public static final int RED = 1;    
    3     public static final int YELLOW = 2;
    4 }
    5 调用方式:ColorConstant.RED;
  • 相关阅读:
    VijosP1274:神秘的咒语
    2009年浙大 :找出直系亲属
    django用户信息扩展
    缓存
    自定义认证
    自定义admin
    权限的配置和使用
    form表单
    过滤器 自定义查询
    中间件
  • 原文地址:https://www.cnblogs.com/zhlblogs/p/9077153.html
Copyright © 2011-2022 走看看