Wednesday, March 11, 2009

Nesting Java enums in an interface

Continuing on my post about enums from yesterday...

Just like a class can be nested inside an interface, an enum can also be nested inside an interface. Nested enums in an interface are implicitly static and public. Here is an example.

interface SoundInterface {
public void makeSound();

//nested enum
enum WesternStringInstruments implements SoundInterface {
PIANO("Piano"), GUITAR("Guitar"),
VIOLIN("Violin"), VIOLA, BASE, CELLO;

private String name;
WesternStringInstruments(){
name = null;
}

WesternStringInstruments(String name) {
this.name = name;
}

@Override public String toString() {
if (name != null) {
return name;
}
return this.name();
}
public void makeSound(){
System.out.println("String sound");
}
}

}

public class InterfaceWithEnum {

//Using the nested enum
public static void main(String[] args) {
for( SoundInterface.WesternStringInstruments st:
SoundInterface.WesternStringInstruments.values()) {
System.out.println(st);
}
SoundInterface.WesternStringInstruments.PIANO.makeSound();
}
}


Here is the output:
Piano
Guitar
Violin
VIOLA
BASE
CELLO
String sound

No comments:

Post a Comment