Saturday, May 25, 2013

Enums in java: Another Example

Here's another example of using enums. Note that the constructor of an enum cannot be public.

checkout the code here

/**
 * An enum for various payment modes.
 * The payment mode also specifies a surcharge to be charged for making payments.
 *
 * @author megha birmiwal
 */
public enum PaymentMode {
        CASH(0),
        CHECK(0.5),
        CREDIT_CARD(1.5),
        DEBIT_CARD(1.0),
        GIFT_CARD(0),
        PAYPAL(1.5),
        MONEY_ORDER(0.3);

        private final double surcharge;

        private PaymentMode(double surcharge) {
                this.surcharge = surcharge;
        }

        public double getSurcharge() {
                return surcharge;
        }
}

/**
 * Lists all payment modes and their surcharges.
 *
 * @author megha birmiwal
 */
public class PaymentModeLister {

        public static void main(String[] args) {
                // .values() returns an array of all possible values
                PaymentMode[] values = PaymentMode.values();
                for (PaymentMode pm : PaymentMode.values()) {
                        System.out.println(pm.name() + " / " + pm.getSurcharge());
                }

                // go from string to the corresponding enum
                PaymentMode pm = PaymentMode.valueOf("PAYPAL");
                System.out.println(pm == PaymentMode.PAYPAL);

                // throws exception because there is no enum value called XYZ
                PaymentMode mode = PaymentMode.valueOf("XYZ");
        }
}

1 comment:

  1. How to login into the casino in 2021
    Here is how kadangpintar to do this: Step 1. Go 도레미시디 출장샵 to the website. · Click on the “Login” link on https://vannienailor4166blog.blogspot.com/ the casino-roll.com right-hand side. · Click on the https://deccasino.com/review/merit-casino/ “Login” button to enter a live chat number. · Enter the

    ReplyDelete