首页 > 编程语言 >enum in Java

enum in Java

时间:2022-11-27 02:55:22浏览次数:87  
标签:Java Color enum public class RED

https://www.geeksforgeeks.org/enum-in-java/

Enumerations serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). 
Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.

A Java enumeration is a class type. Although we don’t need need to instantiate an enum using new, it has the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just like classes, you can give them constructor, add instance variables and methods, and even implement interfaces.

 

One thing to keep in mind is that, unlike classes, enumerations neither inherit other classes nor can get extended(i.e become superclass). 

In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).

 

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

  • Java
 
// A simple enum example where enum is declared // outside any class (Note enum keyword instead of // class keyword)   enum Color {     RED,     GREEN,     BLUE; }   public class Test {     // Driver method     public static void main(String[] args)     {         Color c1 = Color.RED;         System.out.println(c1);     } }
Output
RED
  • Java
 
// enum declaration inside a class.   public class Test {     enum Color {         RED,         GREEN,         BLUE;     }       // Driver method     public static void main(String[] args)     {         Color c1 = Color.RED;         System.out.println(c1);     } }
Output
RED
  • The first line inside the enum should be a list of constants and then other things like methods, variables, and constructors.
  • According to Java naming conventions, it is recommended that we name constant with all capital letters

Important Points of enum:  

  • Every enum is internally implemented by using Class.
/* internally above enum Color is converted to
class Color
{
     public static final Color RED = new Color();
     public static final Color BLUE = new Color();
     public static final Color GREEN = new Color();
}*/
  • Every enum constant represents an object of type enum.
  • enum type can be passed as an argument to switch statements.
  • Java
 
// A Java program to demonstrate working on enum // in switch case (Filename Test. Java)   import java.util.Scanner;   // An Enum class enum Day {     SUNDAY,     MONDAY,     TUESDAY,     WEDNESDAY,     THURSDAY,     FRIDAY,     SATURDAY; }   // Driver class that contains an object of "day" and // main(). public class Test {     Day day;       // Constructor     public Test(Day day) { this.day = day; }       // Prints a line about Day using switch     public void dayIsLike()     {         switch (day) {         case MONDAY:             System.out.println("Mondays are bad.");             break;         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;         }     }       // Driver method     public static void main(String[] args)     {         String str = "MONDAY";         Test t1 = new Test(Day.valueOf(str));         t1.dayIsLike();     } }
Output
Mondays are bad.
  • Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can’t create child enums.
  • We can declare the main() method inside the enum. Hence we can invoke enum directly from the Command Prompt.
  • Java
 
// A Java program to demonstrate that we can have // main() inside enum class.   enum Color {     RED,     GREEN,     BLUE;       // Driver method     public static void main(String[] args)     {         Color c1 = Color.RED;         System.out.println(c1);     } }
Output
RED

Enum and Inheritance:  

  • All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.
  • toString() method is overridden in java.lang.Enum class, which returns enum constant name.
  • enum can implement many interfaces.

values(), ordinal() and valueOf() methods:  

  • These methods are present inside java.lang.Enum.
  • values() method can be used to return all values present inside the enum.
  • Order is important in enums.By using the ordinal() method, each enum constant index can be found, just like an array index.
  • valueOf() method returns the enum constant of the specified string value if exists.
  • Java
 
// Java program to demonstrate working of values(), // ordinal() and valueOf()   enum Color {     RED,     GREEN,     BLUE; }   public class Test {     public static void main(String[] args)     {         // Calling values()         Color arr[] = Color.values();           // enum with loop         for (Color col : arr) {             // Calling ordinal() to find index             // of color.             System.out.println(col + " at index "                                + col.ordinal());         }           // Using valueOf(). Returns an object of         // Color with given constant.         // Uncommenting second line causes exception         // IllegalArgumentException         System.out.println(Color.valueOf("RED"));         // System.out.println(Color.valueOf("WHITE"));     } }
Output
RED at index 0
GREEN at index 1
BLUE at index 2
RED

enum and constructor:  

  • enum can contain a constructor and it is executed separately for each enum constant at the time of enum class loading.
  • We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.

enum and methods:  

  • enum can contain both concrete methods and abstract methods. If an enum class has an abstract method, then each instance of the enum class must implement it
  • Java
 
// Java program to demonstrate that enums can have // constructor and concrete methods.   // An enum (Note enum keyword inplace of class keyword) enum Color {     RED,     GREEN,     BLUE;       // enum constructor called separately for each     // constant     private Color()     {         System.out.println("Constructor called for : "                            + this.toString());     }       public void colorInfo()     {         System.out.println("Universal Color");     } }   public class Test {     // Driver method     public static void main(String[] args)     {         Color c1 = Color.RED;         System.out.println(c1);         c1.colorInfo();     } }
Output
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Next Article on enum: Enum with Customized Value in Java

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

标签:Java,Color,enum,public,class,RED
From: https://www.cnblogs.com/kungfupanda/p/16928902.html

相关文章

  • Generics in Java
    https://www.geeksforgeeks.org/generics-in-java/ Generics means parameterizedtypes.Theideaistoallowtype(Integer,String,…etc.,anduser-defined......
  • java发送邮件
    一邮件协议收发邮件具有与HTTP协议相同的邮件传输协议.SMTP:(SimpleMailTransferProtocol,简单邮件传输协议)发邮件协议POP3:(PostOfficeProtocolVersion3,邮局协议第......
  • Java中YYYY-MM-dd在跨年时出现的bug
    先看一张图:Bug的产生原因:日期格式化时候,把yyyy-MM-dd写成了YYYY-MM-dd Bug分析:当时间是2019-08-31时,publicclassDateTest{publicstaticvoidmain(Strin......
  • java中乐观锁CAS的实现探究——AtomicInteger
    CASCAS——compareandswap,比较并交换。是一种乐观锁的实现方式。更新操作时,在每次更新之前,都先比较一下被更新的目标T,值是不是等于读取到的旧值O,如果相等,则认为在读取......
  • JAVA网络编程TCP实现聊天功能,附在IDEA中同时运行2个或以上相同的java程序
    在IDEA中同时运行2个或以上相同的java程序在日常编写测试代码时,有时候会需要在idea上同时运行两个及以上相同的java程序,如:想运行两个CLIENTLOGIN测试聊天室效果。1.点击E......
  • java9
    Java9新特性Java9发布于2017年9月22日,带来了很多新特性,其中最主要的变化是已经实现的模块化系统。接下来我们会详细介绍Java9的新特性。Java9新特性模块系......
  • 基于java+swing的图书管理系统
    功能展示登录管理员-主界面管理员-增加书籍管理员-更新和删除书籍管理员-查找书籍管理员-查找所有书籍管理员-添加用户管理员-更新和删除用户管理员-查找......
  • Javascript(笔记53) - promise - 3 几个关键问题
    如何改变Promise的状态?1)resolve(value):如果当前是pending 就会变为resolved(或fulfilled); 2)reject(reason):如果当前是pending 就会变为rejected; 3) 抛出异常:如......
  • java中abstract详解
     Abstract(抽象)可以修饰类、方法 如果将一个类设置为abstract,则此类必须被继承使用。此类不可生成对象,必须被继承使用。 Abstract可以将子类的共性最大限度的抽取出来,放......
  • Java基础——继承(Extends)
    使用extends(继承)有什么好处?使用继承可以实现代码的重用,通过继承,子类可以继承父类的成员变量及成员方法,同时子类也可以定义自己的成员变量和成员方法。届时,子类将具有父类......