java基础五(枚举中定义其它结构,枚举的应用)

1.可以在枚举中实现接口,定义属性,实现构造方法等。代码如下

interface IColor {
    public String getColor();
}
enum  Color implements IColor{
    RED("红色"),GREEN("绿色"),BLUE("蓝色"); //如果定义很多内容,枚举对象必须写在第一行
    private String title;
    private Color(String title) {
       this.title = title;
    }

    @Override
    public String toString() {
        return this.title;
    }

    @Override
    public String getColor() {
        return this.title;
    }
}
public class test {
    public static void main(String [] args) {
        System.out.println(Color.GREEN.getColor());
    }
}

2.枚举的应用举例

class Apple {
    private Color color;
    private String name;

    public Apple(Color color, String name) {
        this.color = color;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "color=" + color +
                ", name='" + name + '\'' +
                '}';
    }
}
interface IColor {
    public String getColor();
}
enum  Color implements IColor{
    RED("红色"),GREEN("绿色"),BLUE("蓝色"); //如果定义很多内容,枚举对象必须写在第一行
    private String title;
    private Color(String title) {
       this.title = title;
    }
    @Override
    public String toString() {
        return this.title;
    }

    @Override
    public String getColor() {
        return this.title;
    }
}
public class test {
    public static void main(String [] args) {

        switch (Color.GREEN) {
            case GREEN:System.out.println(Color.GREEN.toString());break;
            case RED:System.out.println(Color.RED.toString());break;
            case BLUE:System.out.println(Color.BLUE.toString());break;
        }
        Apple apple = new Apple(Color.GREEN,"青苹果");
        System.out.println(apple.toString());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值