使用方法的Jjava枚举? [英] Jjava enumerations with methods ?

查看:77
本文介绍了使用方法的Jjava枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..

我看过一些枚举,其中包含大括号内每个对象的方法,如下例所示。



Hi..
Ive seen some enumerations with methods for each object inside curly brackets like the example below..

enum Pet
{
    Cat
    {
        public void printName()
        {
            System.out.println("Name of the cat");
        }
    },
    Dog
    {
        public void printName()
        {
            System.out.println("Name of the dog");
        }
    };
}





我想知道这个方法printName()的用途是什么..

我如何使用这些方法?



谢谢....



And I wanna know what's the uses of this method printName()..
How can I use those methods ?

Thanks....

推荐答案

参见括号内的值的枚举 [ ^ ]并按照问题中的链接进行教程主题。



我刚注意到你的问题,所以它已经提供了答案。
See Enums with values inside brackets[^] and follow the link in the question to a tutorial on the subject.

I just noticed that is your question, so it already provides the answer.


据我所知,特定值的方法是一般枚举方法的覆盖,它可能有一个空体。试试这个:

As far as I can gather the value specific methods are overrides of a general enum method, Which could have an empty body. Try this:
public class Days {

    public enum Day {
        Monday(false) {
            public void showIt() {
                System.out.println("It's the beginning of the week");
            }
        },
        Tuesday(false),
        Wednesday(false),
        Thursday(false),
        Friday(false) {
            public void showIt() {
                System.out.println("The weekend starts here");
            }
        },
        Saturday(true),
        Sunday(true);
 
        private final boolean weekEnd;
    
        Day(boolean weekEnd) {
            this.weekEnd = weekEnd;
        }
        boolean isWeekend() {
            return weekEnd;
        }
        public void showIt() {
        }
    }
    public static void main(String[] args) throws Exception {
        for (Day d: Day.values()) {
           System.out.print(d);
           if (d.isWeekend())
               System.out.print(" is not");
           else
               System.out.print(" is");
           System.out.println(" a weekday");
           d.showIt();
        }
    }
}


这篇关于使用方法的Jjava枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆