Last active
September 4, 2018 10:41
-
-
Save seraekim/e8eeac17599f311f06ef590e7f000fba to your computer and use it in GitHub Desktop.
java enum tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.srkim.test; | |
public class java_enum { | |
// public enum Currency {PENNY, NICKLE, DIME, QUARTER}; | |
// public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)}; | |
public enum Currency { | |
PENNY(1) { @Override public String color() {return "copper";}}, | |
NICKLE(5) { @Override public String color() {return "bronze";}}, | |
DIME(10) { @Override public String color() {return "silver";}}, | |
QUARTER(25) { @Override public String color() {return "silver";}}; | |
private int value; | |
public abstract String color(); | |
private Currency(int value) { | |
this.value = value; | |
} | |
@Override | |
public String toString() { | |
switch (this) { | |
case PENNY:System.out.println("Penny: " + value);break; | |
case NICKLE:System.out.println("Nickle: " + value);break; | |
case DIME:System.out.println("Dime: " + value);break; | |
case QUARTER:System.out.println("Quarter: " + value); | |
} | |
return super.toString(); | |
} | |
// @Override | |
// public void run() { | |
// System.out.println("Enum in Java implement interfaces"); | |
// } | |
}; | |
public static void main(String[] args) { | |
Currency usCoin = Currency.DIME; | |
switch (usCoin) { | |
case PENNY: | |
System.out.println("Penny coin"); | |
break; | |
case NICKLE: | |
System.out.println("Nickle coin"); | |
break; | |
case DIME: | |
System.out.println("Dime coin"); | |
System.out.println(usCoin.value); | |
break; | |
case QUARTER: | |
System.out.println("Quarter coin"); | |
} | |
if(usCoin == Currency.DIME){ | |
System.out.println("enum in java can be "+ | |
"compared using =="); | |
} | |
for(Currency coin: Currency.values()){ | |
System.out.println("coin: " + coin); | |
} | |
System.out.println(usCoin); | |
System.out.println("Color: " + Currency.DIME.color()); | |
System.out.println(Currency.DIME.name()); | |
System.out.println(Currency.DIME.ordinal()); | |
System.out.println(Currency.valueOf("PENNY")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment