我们在写java程序的时候,常常有常量设置,如:

  

1 public interface Const {
2 
3     //性别的常量
4     public interface Sex{
5         public final int 男=1;//
6         public final int 女=2;//
7     }
8     
9 }

这种设置方法通过接口向外发布常量。但是却有不足之处。它在类型安全与使用方面没有任何帮助。

java常量设置的方式

因此,我们可以采用java提供的枚举类来实现常量的设置。

以上的可以修改为:

 1 public interface Const {
 2 
 3     //性别的常量
 4     public enum Sex{
 5         男(1),女(2);
 6         private int i;
 7         private Sex(int i){
 8             this.i=i;
 9         }
10         public int getI() {
11             return i;
12         }
13     
14     }
15     
16 }

 

相关文章:

  • 2023-03-07
  • 2021-09-24
  • 2022-12-23
  • 2021-12-19
  • 2021-10-12
  • 2021-12-05
  • 2023-01-31
猜你喜欢
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2022-01-10
  • 2021-09-30
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案