JavaAPI学习——java.lang(三)

发布时间:2019-11-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了JavaAPI学习——java.lang(三)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

二、类

1、Enum 枚举

  • java 语言所有枚举类型的公共类;
  • 枚举用来替换使用常量表示列入颜色、方式、类别等数量有限,形式离散有表示明确的量;
  • 枚举是类型安全的,超出枚举类型的返回,将会发生编译时错误;

例:

  • 使用常量来表示颜色:
public class EntITy{     public static final int red = 1;     public static final int white = 2;     public static final int blue = 3;     PRivate int id;     private int color;          public Entity(int id, int color){         this.id = id;         this.color = color;     }          //id与color的getter 和setter方法     ...      }

实例化一个Entity对象时:

Entity entity = new Entity(); entity.setId(10); entity.setColor(1);

或者

Entity entity = new Entity(); entity.setId(10); entity.setColor(Entity.red);

使用第一种方式,代码的可读性低,1到底代表的什么颜色,需要到Entity类中查看;
使用第二种方式,同样需要去Entity类中查看代码,才能知道怎么调用,参数要怎么传。

  • 使用枚举来表示颜色
//Color.java package com.heisenberg.Learn;  public enum Color {     red,blue,white } //Entity.java package com.heisenberg.Learn;  public class Entity {     private Color color;     private int id;     public Color getColor() {         return color;     }     public void setColor(Color color) {         this.color = color;     }     public int getId() {         return id;     }     public void setId(int id) {         this.id = id;     }          public static void main(String[] args) {         Entity entity = new Entity();         entity.setId(10);         entity.setColor(Color.blue);     } } 

使用枚举,代码的可读性提升了,并且在给color赋值时,只能选择Color枚举类中定义的三个选项,所以枚举是类型安全的,如果使用了另外的值,将出现编译错误。

  • java中的枚举是一个类,所以枚举也可一后构造函数和其他的方法;只是枚举继承了Enum类,所以它不能再继承其它的类。
  • 如果给每个枚举值指定属性,则必须给枚举类提供枚举值属性对应数据类型的构造方法。如下,Color的每个枚举值都带有一个int和一个String类型的属性,则必须提供Color(int value,String name)的构造方法;属性的名称不受限制,但是属性的类型要一一对应。
//Color.java package com.heisenberg.Learn;  public enum Color {     red(1,"红色"),blue(2,"蓝色"),white(3,"白色");          int value;     String name;     private Color(int value, String name) {         this.value = value;         this.name = name;     }     public int getValue() {         return value;     }     public void setValue(int value) {         this.value = value;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     } } 
public static void main(String[] args) {         Entity entity = new Entity();         entity.setId(10);         entity.setColor(Color.blue);         System.out.println(entity.getColor().getValue());         System.out.println(entity.getColor().getName());     }

运行的结果为:


蓝色@H_613_406@

脚本宝典总结

以上是脚本宝典为你收集整理的JavaAPI学习——java.lang(三)全部内容,希望文章能够帮你解决JavaAPI学习——java.lang(三)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。