【问题标题】:have a static method use a non-static member in enum有一个静态方法在枚举中使用一个非静态成员
【发布时间】:2015-04-02 20:24:27
【问题描述】:

我有以下代码:

private enum DateFormats {
        DDMMYYYY(0, 2, 4),
        MMDDYYYY(2, 0, 4),
        YYYYMMDD(6, 4, 0);

        private final int dayIndex;
        private final int monthIndex;
        private final int yearIndex;

        private DateFormats(int dayIndex, int monthIndex, int yearIndex) {
            this.dayIndex = dayIndex;
            this.monthIndex = monthIndex;
            this.yearIndex = yearIndex;
        }

        //Error happens here...
        private static int getDay(String date){ return Integer.parseInt(date.substring(dayIndex, dayIndex+2)); }
        private static int getMonth(String date){ return Integer.parseInt(date.substring(monthIndex, monthIndex+2)); }
        private static int getYear(String date){ return Integer.parseInt(date.substring(yearIndex, yearIndex+4)); }
    }

我得到的错误:

non-static variable dayIndex cannot be referenced from a static context
        private static int getDay(String date){ return Integer.parseInt(date.substring(dayIndex, dayIndex+2)); }

我了解错误的发生是因为该函数是静态的,并且正在使用尚未设置的非静态成员来解析整数。

我在这里查看了很多关于这个的帖子,但我仍然无法理解最好的方法是什么。

非常感谢任何帮助。

【问题讨论】:

  • 错误是什么?为什么方法声明为静态的?
  • 这些方法的目的是什么?为什么他们是private?还有你为什么要让他们static
  • @MickMnemonic 我更新了我的问题
  • 正如@Pshemo 已经说过的,你为什么要让他们staticstatic 方法无权访问实例变量。
  • 但是当你声明它们时你正在创建枚举实例。这就是枚举在 Java 中的工作方式。

标签: java enums static-methods non-static


【解决方案1】:

当您创建枚举时,您拥有三个实例:

DDMMYYYY(0, 2, 4),
MMDDYYYY(2, 0, 4),
YYYYMMDD(6, 4, 0);

每个实例都有三个字段,dayIndexmonthIndexyearIndex。当你这样做时:

DateFormats.DDMMYYYY.getDay()

您在DDMMYYYY 实例上调用getDay(),并且您希望getDay() 使用您在构造函数中设置的特定实例变量,因此getDay() 是静态的没有意义。

例如:

String date = "12052015";
int day1 = DateFormats.DDMMYYYY.getDay(date);
int day2 = DateFormats.MMDDYYYY.getDay(date);
System.out.println(day1);
System.out.println(day2);

结果:

12
05

另外,我不明白为什么 getDay()getMonth()getYear() 应该是私有的,除非您只想从外部类访问它们。

【讨论】:

  • 我不明白为什么 getDay()、getMonth() 和 getYear() 应该是私有的”一个原因可能是 OP 只想在外部类的范围(也可以访问其内部类的私有成员)。
  • @Pshemo 是的,这就是我想要的。在外部类的一个方法中,我想这样称呼它:int day = DateFormats.getDay(date);
  • @Pshemo 好点!我没有看到关于枚举是嵌套类的评论。
  • @Nilzone- "在外部类的方法中我想这样称呼它:int day = DateFormats.getDay(date);" 但是getDay 应该如何知道date 的格式拥有?使用DateFormats.DDMMYYYY.getDay(date)之类的东西不是更好吗?
  • @Nilzone- 在这种情况下,您的方法不应该是 static,因为它们应该使用为每种格式设置的值。
猜你喜欢
  • 1970-01-01
  • 2012-03-31
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多