码迷,mamicode.com
首页 > 其他好文 > 详细

定义常量的几种方式与调用

时间:2018-05-23 16:07:56      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:tin   枚举类型   bsp   style   print   必须   nal   system   for   

 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;

 

定义常量的几种方式与调用

标签:tin   枚举类型   bsp   style   print   必须   nal   system   for   

原文地址:https://www.cnblogs.com/zhlblogs/p/9077153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!