In this Enumerated type the programming is finite set of symbolic names that represent the values of an attribute.
For Example to represent the days of week you can create a set of symbols:
{MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}.
As Example:-
public enum Days {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
Java Enum Code Example :
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package testproject; /** * * @author Droid */ public class JavaTalkEnum { public enum SOLARSYSTEM { EARTH, SUN, MOON, SATURN, MARS, VENUS, JUPITER } SOLARSYSTEM ourSolarSystem; public JavaTalkEnum(SOLARSYSTEM ourSolarSystem) { this.ourSolarSystem = ourSolarSystem; } public void tellItLikeItIs() { switch (ourSolarSystem) { case SUN: System.out.println("SUN is source Of Energy and Center of our Solar System"); break; case VENUS: System.out.println("Venus is second closest planet to the sun"); break; case JUPITER: System.out.println("Jupiter is the largest planet in the Solar System"); break; case EARTH: System.out.println("Earth is Blue Planet and our home."); break; case MOON: System.out.println("MOON revolve around planets, Earth have one moon"); break; case SATURN: System.out.println("Saturn is second largest planet in the Solar System"); break; case MARS: System.out.println("Mars is second smallest planet in the Solar System"); break; default: System.out.println("Sun and objects orbiting around make our solar system"); break; } } public static void main(String[] args) { JavaTalkEnum sun = new JavaTalkEnum(SOLARSYSTEM.SUN); sun.tellItLikeItIs(); JavaTalkEnum saturn = new JavaTalkEnum(SOLARSYSTEM.SATURN); saturn.tellItLikeItIs(); JavaTalkEnum venus = new JavaTalkEnum(SOLARSYSTEM.VENUS); venus.tellItLikeItIs(); JavaTalkEnum jupiter = new JavaTalkEnum(SOLARSYSTEM.JUPITER); jupiter.tellItLikeItIs(); JavaTalkEnum earth = new JavaTalkEnum(SOLARSYSTEM.EARTH); earth.tellItLikeItIs(); JavaTalkEnum moon = new JavaTalkEnum(SOLARSYSTEM.MOON); moon.tellItLikeItIs(); JavaTalkEnum mars = new JavaTalkEnum(SOLARSYSTEM.MARS); mars.tellItLikeItIs(); } } Output : SUN is source Of Energy and Center of our Solar System Saturn is second largest planet in the Solar System Venus is second closest planet to the sun Jupiter is the largest planet in the Solar System Earth is Blue Planet and our home. MOON revolve around planets, Earth have one moon Mars is second smallest planet in the Solar System
Hope this example help you to understand enum in Java.
0 comments:
Post a Comment