Enumeration classes in Java

Source: Internet
Author: User

Enum Class (enum), which is the same as the class and interface keywords.

An enumeration class is a special class that can have its own member variables, methods, constructors, and can implement one or more interfaces. There can be only one enum class of public in a Java source file.

The enumeration class is not an ordinary class after all, what is the difference between it and the ordinary class?

The enum inherits by default the Java.lang.Enum class, not the object class. An enum class cannot explicitly inherit other parent classes.

Enum classes that use enum definitions and non-abstractions use the final adornment by default, so the enum class cannot be inherited (cannot derive subclasses).

The constructor for an enumeration class can only be decorated with private.

All instances of an enumeration class can be explicitly listed only in the first row of the enumeration class. The public static final adornment is added automatically, and the programmer does not need to add it explicitly.

The enumeration class provides a values () method that makes it easy to traverse the value of an enum.

public enum seasonenum{
List of 4 enumerated instances
Sring,summer,fall,winter; }

This class is equivalent to:

public static final int season_spring=1;public static final int season_summer=2;public static final int Season_fall=3;publ IC static final int season_winter=4;

  

Ways to traverse the Seasonenum class:

public class Enumtest
{
public void judge (Seasonenum s)
{
Switch (s)
{
Case Sring:
Syso ("Spring");
Break
Case SUMMER:
SYSO ("Summer");
Break
......
}
}

Main method Main () {for (Seasonenum s:seasonenum.values ())
{
SYSO (s);
}

New Enumtest (). Judge (Seasonenum.summer);//Use the class name of the enumeration class Seasonenum invoke instance
}
}

  

Enumeration classes in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.