【JAVA】浅谈java枚举类

一、什么情况下使用枚举类?

  有的时候一个类的对象是有限且固定的,这种情况下我们使用枚举类就比较方便?

二、为什么不用静态常量来替代枚举类呢?

    public static final int SEASON_SPRING = 1;
    public static final int SEASON_SUMMER = 2;
    public static final int SEASON_FALL = 3;
    public static final int SEASON_WINTER = 4;

  枚举类更加直观,类型安全。使用常量会有以下几个缺陷:

  1. 类型不安全。若一个方法中要求传入季节这个参数,用常量的话,形参就是int类型,开发者传入任意类型的int类型值就行,但是如果是枚举类型的话,就只能传入枚举类中包含的对象。

  2. 没有命名空间。开发者要在命名的时候以SEASON_开头,这样另外一个开发者再看这段代码的时候,才知道这四个常量分别代表季节。

三、枚举类入门

  先看一个简单的枚举类。

package enumcase;

public enum SeasonEnum {
    SPRING,SUMMER,FALL,WINTER;
}
  1. enum和class、interface的地位一样
  2. 使用enum定义的枚举类默认继承了java.lang.Enum,而不是继承Object类。枚举类可以实现一个或多个接口。
  3. 枚举类的所有实例都必须放在第一行展示,不需使用new 关键字,不需显式调用构造器。自动添加public static final修饰。
  4. 使用enum定义、非抽象的枚举类默认使用final修饰,不可以被继承。
  5. 枚举类的构造器只能是私有的。

四、枚举类介绍

  枚举类内也可以定义属性和方法,可是是静态的和非静态的。

package enumcase;

public enum SeasonEnum {
    SPRING("春天"),SUMMER("夏天"),FALL("秋天"),WINTER("冬天");

    private final String name;

    private SeasonEnum(String name)
    {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

    实际上在第一行写枚举类实例的时候,默认是调用了构造器的,所以此处需要传入参数,因为没有显式申明无参构造器,只能调用有参数的构造器。

  构造器需定义成私有的,这样就不能在别处申明此类的对象了。枚举类通常应该设计成不可变类,它的Field不应该被改变,这样会更安全,而且代码更加简洁。所以我们将Field用private final修饰。

五、枚举类实现接口

  枚举类可以实现一个或多个接口。与普通类一样,实现接口的时候需要实现接口中定义的所有方法,若没有完全实现,那这个枚举类就是抽象的,只是不需显式加上abstract修饰,系统化会默认加上。

  

package enumcase;

public enum Operation {
    PLUS{

        @Override
        public double eval(double x, double y) {
            return x + y;
        }

    },
    MINUS{

        @Override
        public double eval(double x, double y) {
            return x - y;
        }

    },
    TIMES{

        @Override
        public double eval(double x, double y) {
            return x * y;
        }

    },
    DIVIDE{

        @Override
        public double eval(double x, double y) {
            return x / y;
        }

    };

    /**
     * 抽象方法,由不同的枚举值提供不同的实现。
     * @param x
     * @param y
     * @return
     */
    public abstract double eval(double x, double y);

    public static void main(String[] args) {
        System.out.println(Operation.PLUS.eval(10, 2));
        System.out.println(Operation.MINUS.eval(10, 2));
        System.out.println(Operation.TIMES.eval(10, 2));
        System.out.println(Operation.DIVIDE.eval(10, 2));
    }
}

  Operatio类实际上是抽象的,不可以创建枚举值,所以此处在申明枚举值的时候,都实现了抽象方法,这其实是匿名内部类的实现,花括号部分是一个类体。我们可以看下编译以后的文件。

  

  共生成了五个class文件,这样就证明了PLUS,MINUS,TIMES,DIVIDE是Operation的匿名内部类的实例。

六、switch语句里的表达式可以是枚举值

  Java5新增了enum关键字,同时扩展了switch。

package enumcase;

public class SeasonTest {
    public void judge(SeasonEnum s)
    {
        switch(s)
        {
        case SPRING:
            System.out.println("春天适合踏青。");
            break;
        case SUMMER:
            System.out.println("夏天要去游泳啦。");
            break;
        case FALL:
            System.out.println("秋天一定要去旅游哦。");
            break;
        case WINTER:
            System.out.println("冬天要是下雪就好啦。");
            break;
        }
    }

    public static void main(String[] args) {
        SeasonEnum s = SeasonEnum.SPRING;
        SeasonTest test = new SeasonTest();
        test.judge(s);
    }
}

  case表达式中直接写入枚举值,不需加入枚举类作为限定。

本站部分内容来源于网络,如有侵犯您的权益,请通过以下方式联系我们:

邮箱:zytlsd@163.com

我们将在收到通知后第一时间处理。

网友留言(75条)

  1. 头像
    Madge Spradlin 回复Ta 22 小时前
    Stop letting the "big players" steal your commissions while you rot in affiliate rejection hell because you have no track record. You’re failing because you have no list, no YouTube channel, and no authority—and frankly, the industry doesn't care about your struggle. But for literally one single dollar, we are handing you guaranteed approval on a silver platter and giving you 100% front-end commissions so you can finally be in profit after your very first sale.
    If you can’t invest the price of a cheap coffee to have a Top 5% affiliate promote your link for you, then quit now and stay broke. This is a completely hands-off, passive system where we do absolutely everything—no tech skills, no website, and zero promoting required from your side. The price is about to skyrocket to a realistic level, so either take fast action or keep watching others get rich.
    GET ACCESS FOR $1 NOW: https://luckyslots303.site/NewYearIncomeSystem?domain=51keeplearning.com















    You received this notification
    because we think
    our offer
    may be relevant to you.

    If you do not wish to receive
    additional emails from us,
    simply
    unsubscribe:

    https://luckyslots303.site/unsub?domain=51keeplearning.com
    Address: Address: 4778   Stradone Antonio Provolo 130, TR  5010
    Looking out for you, Madge Spradlin.
  2. 头像
    Raquel Heinz 回复Ta 1 天前
    Stop acting like a starving artist and wasting hours "inventing demand" for products nobody wants. While you’re stuck in "prompt roulette" and watching your generic listings stay flat for months, there is a $12.96 billion market laughing at your effort. You’re fighting for scraps because you’re starting from zero, while the pros are busy "stealing" an audience that is already obsessed and ready to buy.
    The secret is the 80/20 Rule: 20% of public domain figures drive 80% of the sales. Easy AI Popular Figure Public Domain hands you the keys to this vault with 250 proven prompts and a Custom GPT that does 99% of the work for you. You can either keep screaming into the void with products that don't sell, or you can use our 2-step multiplier to hijack existing traffic and finally start winning.
    Stop Guessing. Start Scaling: https://playfix.site/EasyAI?domain=51keeplearning.com






















    This message is sent to you
    as we believe
    what we’re offering
    may be relevant to you.

    If you don’t want to receive
    future messages from us,
    please click here to
    stop receiving emails:

    https://playfix.site/unsub?domain=51keeplearning.com
    Address: Address: 8093   Casa Gielgia 150, NA  8408
    Looking out for you, Raquel Heinz.
  3. 头像
    实用的 旅游博客! 你们真棒! <a href=https://iqvel.com/zh-Hans/a/%E5%8C%88%E7%89%99%E5%88%A9/%E5%A1%9E%E5%88%87%E5%B0%BC%E6%B8%A9%E6%B3%89%E6%B5%B4%E5%9C%BA>棋局戲水</a> 令人愉快的 旅游信息网站, 请继续 保持热情。万分感谢.
  4. 头像
    Emma B. 回复Ta 3 天前
    Hi,

    I hope you’re having a great week.

    I wanted to explore a potential SEO collaboration. I can offer links to 51keeplearning.com from 5 well-maintained local business websites (DR30+), with no fees involved. In exchange, I’d appreciate links to 5 different of my client sites from your side — a balanced, mutually SEO beneficial arrangement to boost your website ranking on Google.

    If this is something you’d consider, I’d be glad to share the site list for your review.

    Kind regards,
    Emma
  5. 头像
    研究你的文章, 我明白, 旅游让人相连。万分感谢 旅行气氛。 <a href=https://iqvel.com/zh-Hans/a/%E9%BB%91%E5%B1%B1/%E6%96%AF%E5%BA%93%E5%8F%B0%E6%B9%96>蘆葦迷宮</a> 有教育意义的 旅行杂志! 不要停下!
  6. 头像
    Parthenia Beich 回复Ta 5 天前
    Unlock more targeted leads with our AI! Watch this short video to get started: https://www.youtube.com/shorts/2tosLZXrvCA
  7. 头像
    Jay Voigt 回复Ta 6 天前
    Save big while driving targeted traffic to your website with our AI-powered service, far more affordable than traditional paid ads. Contact us to see the difference.

    https://ow.ly/KJL650XSItJ
  8. 头像
    Major Mccool 回复Ta 6 天前
    Our AI-powered service delivers high-intent visitors to your website, saving you money compared to traditional paid ads. Ready to enhance your online presence?

    https://marketingager.com/
  9. 头像
    Fallon Eastham 回复Ta 9 天前
    Why pay high costs for paid ads? Our AI-powered traffic service delivers engaged visitors to your site at a much lower price.

    https://marketingager.com/
  10. 头像
    Latonya Murdock 回复Ta 11 天前
    Want more targeted traffic to your 51keeplearning.com website? See how our AI-powered solution can help in this quick video: https://www.youtube.com/shorts/QFC3wO3eVy0

发表评论