Monday, April 28, 2025

Java OO Tutorial - Enums

Enums in Java are a special data type that allow you to define a set of constants with a specific name and value. They are used to represent a fixed set of values that don't change during the execution of the program. Enum constants are static and final by default.

In Java, you define an enum using the enum keyword followed by the name of the enumeration. 

enum Options {
	AUDIO,
	VIDEO,
	CONTROLS
}

public class Main {	
	
	public static void main(String[] args) {
		
		for (Options someObj : Options.values()) {
			System.out.println(someObj);
		}
		
		/*
		Options inputObj = Options.VIDEO;
		
		switch(inputObj) {
		case AUDIO:
			System.out.println("Audio Settings");
			break;
		case VIDEO:
			System.out.println("Video Settings");
			break;
		case CONTROLS:
			System.out.println("Joystick and Keyboard Settings");
			break;		
		}*/				
	}		
}

Here's an explanation of the code block by block: 

enum Options {
	AUDIO,
	VIDEO,
	CONTROLS
}

This defines an enum called Options with three possible values: AUDIO, VIDEO, and CONTROLS

public class Main {	
	
	public static void main(String[] args) {
		...
	}
}

This defines a class called Main with a main method. 

for (Options someObj : Options.values()) {
	System.out.println(someObj);
}

This loop iterates over all the possible values of the Options enum using the values method, and prints each value to the console. 

/*
Options inputObj = Options.VIDEO;

switch(inputObj) {
case AUDIO:
	System.out.println("Audio Settings");
	break;
case VIDEO:
	System.out.println("Video Settings");
	break;
case CONTROLS:
	System.out.println("Joystick and Keyboard Settings");
	break;		
}*/

This is a commented out code block that demonstrates how enum values can be used in a switch statement. Here, VIDEO is used as the input object, and the switch statement checks which value it matches and prints out the corresponding message.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...