0% found this document useful (0 votes)
42 views

Introduction To Programming 1

An enum type defines a fixed set of constants that can be used as fields. The document provides examples of how to define an enum called Day with weekday constants, how to iterate through the enum values, and how to define methods within the enum class. Methods within an enum can access and compare the enum values.

Uploaded by

eragol
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Introduction To Programming 1

An enum type defines a fixed set of constants that can be used as fields. The document provides examples of how to define an enum called Day with weekday constants, how to iterate through the enum values, and how to define methods within the enum class. Methods within an enum can access and compare the enum values.

Uploaded by

eragol
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

J9a Enum type

Introduction to Programming 1 1
Enum
● An enum type is a type whose fields consist of a
fixed set of constants.

public enum Day { SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

Introduction to Programming 1 2
Example 1
public class EnumTest {
Day day;

public EnumTest(Day day) {


this.day = day;
}

public void tellItLikeItIs() {


switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;

Introduction to Programming 1 3
Example 1
case FRIDAY:
System.out.println("Fridays are better.");
break;

case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-
so.");
break;
}
}

Introduction to Programming 1 4
Example 2
● have a static values method that returns an array
containing all of the values

for (Day d : Day.values()) {

System.out.println("The day is:” +


d.toString());
}

Introduction to Programming 1 5
Example 3
● The enum class body can include methods and
other fields (not necessarily static)
● an enum cannot be instantiated
public class Main {

Day d;
enum Day { SUN,MON,TUES;

public boolean isMon(Day a) {


return (a==Day.MON);
}
}

Introduction to Programming 1 6
Example 3

public static void main(tring[] args) {


Main m = new Main();

Day d1 = m.d;
d1 = Day.TUES;
boolean ans = d1.isMon(d1);

}
}

Introduction to Programming 1 7

You might also like