/* * [TestEnumMagic.java] * * Summary: Demonstrates a "magic" feature of enums. * * Copyright: (c) 2016-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2016-06-08 initial version */ package com.mindprod.example; import static java.lang.System.*; /** * Demonstrates a "magic" feature of enums. *

* Even though you call a common method, not attached to any particular enum, * it gets the copy of the value associated with the enum constrant doing the call, * in this case, one set by the constructor. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2016-06-08 initial version. * @since 2016-06-08 */ public enum TestEnumMagic { HONEY( "bee" ) { public void show() { out.println( "via honey: " + getAnimal() ); // prints bee } }, MILK( "cow" ) { public void show() { out.println( "via milk: " + getAnimal() ); // prints cow } }; private final String animal; /** * constructor */ TestEnumMagic( final String animal ) { this.animal = animal; } String getAnimal() { return this.animal; } /** * without this tying the two shows together, you will not be able to acceess show from main. */ abstract void show(); public static void main( String[] args ) { HONEY.show(); MILK.show(); } }