【问题标题】:Java enum methodJava枚举方法
【发布时间】:2016-08-24 00:33:59
【问题描述】:

以下代码编译运行没有问题。但我的问题是 public int getValue(int bid) [ NOT getValues(int bid) 有什么用?我将如何调用该方法?

package com.main;
public class Bridge {

    public enum Suites{
        CLUB(20), DIMOND(20), HEARTS(30), SPADES(40){ 
            public int getValue(int bid){
                return ((bid-1)*30)+40;
            }
        };
        private int points;
        Suites(int points){
            this.points = points;

        }

        public int getValues(int bid){
            return points*bid;
        }

    }

    public static void main(String[] args){
        System.out.println(Suites.CLUB.getValues(3));
        System.out.println(Suites.HEARTS.points);
        System.out.println(Suites.values());
    }

}
输出是: 60 30 [Lcom.main.Bridge$Suites;@2a139a55

【问题讨论】:

  • 它没有目的,不能调用,除非通过反射。这可能是一个错字,我投票决定关闭。
  • 在英文中,类别称为“Suits”,其值为“Spades”、“Clubs”、“Diamonds”和“Hearts”。你有几个错别字。

标签: java enums


【解决方案1】:

为 SPADES 指定的 getValue 方法的唯一用例是,如果为 Suites 枚举指定了具有相同 and 和签名的方法,例如像这样:

public class Test {

    public enum Suites {
        CLUB(20),
        DIMOND(20),
        HEARTS(30),
        SPADES(40) {
            @Override
            public int getValue(int bid) {
                return ((bid - 1) * 30) + 40;
            }
        };
        private int points;

        Suites(int points) {
            this.points = points;

        }

        public int getValue(int bid) {
            return bid;
        }

        public int getValues(int bid) {
            return points * bid;
        }

    }

    public static void main(String[] args) {
        for (Suites suite : Suites.values()) {
            System.out.println(suite.name() + ": getValue: " + suite.getValue(1));
        }
    }
}

这将输出

CLUB: getValue: 1
DIMOND: getValue: 1
HEARTS: getValue: 1
SPADES: getValue: 40

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多