枚举上的调用方法

枚举上的调用方法

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

问题描述

public enum AgeGroup {
        CHILD{
           public int get(){
               return 10;
           }
        },
        TEEN, YOUNG, MID, OLD;
    }

我有一个枚举 AgeGroup 并且正如您看到 CHILD 有一个方法 get()。有人可以告诉我为什么我们不能从 CHILD 调用 get()是否这样设计?

I have an enum AgeGroup and as you are seeing that CHILD has one method get(). Can somebody tell me why we can't call get() from CHILD what is the design approach behind this or why is it designed like this?

推荐答案

首先,枚举的所有实例都是相同类型的 ,这意味着所有实例都具有相同的方法

Firstly, all instances of an enum are of the same type, which means all instances have the same set of methods.

您需要在枚举类型本身上声明一个方法,以使实例具有方法:

You need to declare a method on the enum type itself for instances to have a method:

public enum AgeGroup {
    CHILD{
       public int get(){
           return 10;
       }
    },
    TEEN, YOUNG, MID, OLD;
    public int get() {
        return 0;
    }
}

如果所有实例都覆盖了 get()方法为 CHILD 已经可以声明方法为 abstract 强制编码器在添加新实例时实现该方法。

If all instances overrode the get() method as CHILD has, you could declare the method as abstract, which forces the coder to implement the method if new instances are added.

最好的方法是使用 final 字段通过一个自定义的构造函数初始化一个getter:

The best approach is to use a final field, initialized via a custom constructor, with a getter:

public enum AgeGroup {
    CHILD{10), TEEN(19), YOUNG(35), MID(50), OLD(80);
    private final int age;
    AgeGroup(int age) {
        this.age = age;
    }
    public int get() {
        return
    }
}

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

08-14 19:26