- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we define an enum inside a class in Java?
Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax
enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
Example
public class EnumerationExample { enum Enum { Mango, Banana, Orange, Grapes, Thursday, Apple } public static void main(String args[]) { Enum constants[] = Enum.values(); System.out.println("Value of constants: "); for(Enum d: constants) { System.out.println(d); } } }
Output
Value of constants: Mango Banana Orange Grapes Thursday Apple
Example
enum Vehicles { //Declaring the constants of the enum ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER; int i; //Instance variable Vehicles() { //constructor } public void enumMethod() { //method System.out.println("Current value: "+Vehicles.this); } } public class Sam{ public static void main(String args[]) { Vehicles vehicles[] = Vehicles.values(); for(Vehicles veh: vehicles) { System.out.println(veh); } vehicles[3].enumMethod(); } }
Output
ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Current value: VESPA
Advertisements