воскресенье, 10 марта 2024 г.

Enums in Java

    The Enum is a data type which contains a fixed set of constants. The Java enum constants are static and final implicitly.

  • Points to remember for Java Enum
  • Enum improves type safety
  • Enum can be easily used in switch
  • Enum can be traversed
  • Enum can have fields, constructors and methods
  • Enum may implement many interfaces but cannot extend any class because it internally extends Enum class
xcxcxcxc

public enum TrafficSignal {
RED("Stop", 30),
YELLOW("Prepare to Stop", 5),
GREEN("Go", 45);

private final String action;
private final int durationSeconds;

// Constructor
TrafficSignal(String action, int durationSeconds) {
this.action = action;
this.durationSeconds = durationSeconds;
}

// Method to get the action associated with the traffic signal
public String getAction() {
return action;
}

// Method to get the duration of the signal in seconds
public int getDurationSeconds() {
return durationSeconds;
}
}

public class Main {
public static void main(String[] args) {
// Using enum constants
TrafficSignal redSignal = TrafficSignal.RED;
TrafficSignal greenSignal = TrafficSignal.GREEN;

// Accessing fields and methods
System.out.println("Red signal: " + redSignal.getAction() + " for " +
redSignal.getDurationSeconds() + " seconds");
System.out.println("Green signal: " + greenSignal.getAction() + " for " +
greenSignal.getDurationSeconds() + " seconds");
}
}

Constructor of enum type is private. If you don't declare private compiler internally creates private constructor.

public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

public class Main {
public static void main(String[] args) {
// Retrieves the enum constant associated with the specified string
Day day = Day.valueOf("MONDAY");
System.out.println("Day retrieved using valueOf(): " + day);

// Returns an array containing all of the enum constants
Day[] days = Day.values();
System.out.println("All days retrieved using value():");
for (Day d : days) {
System.out.println(d);
}

// Returns the ordinal value of the enum constant
System.out.println("Ordinal value of TUESDAY: " + Day.TUESDAY.ordinal());
}
}

Комментариев нет:

Отправить комментарий