Effective Java enum class

Source: Internet
Author: User

With the effective Java this book to see more and more, found in peacetime use of Java made a lot of obvious mistakes, they usually know a little but the lack of use is also more and more.

As for enumeration classes, the suggestion in the book is to replace the traditional static constants with enumeration classes, usually, if a class of data is represented by a different numeric value, it is normal for me to write a series of const static constants to express, but after reading this book it is found that this method can achieve its own purpose, but there are some hidden dangers, For example, type safety, and when using the above method to distinguish between different types, a particular type of method is used outside the judgment and then call, in this case, the code becomes not very beautiful.

There are four basic data types in Java, namely the basic data type, the array type, the class type, and the interface type, the enumeration class should belong to the class type, and since the enumeration class belongs to one of the class types, the enumeration class should have some attributes of the class type, such as construction method, member variable, member method, etc. This is the enumeration type not only has to distinguish the different categories of functions, and even can add their own methods for different types, of course, to implement an interface before the line, and implement some of these types of public methods, so the enumeration type to represent different types, it is more flexible than with different static constants.

The difference between an enumeration type and a normal class type should be that each object in the enumeration type is singleton, so in singleton mode, the most recommended singleton pattern is the one that is implemented by enumeration. Of course, enum types are not in any case more advantageous than static constants, such as in the case of constrained resources, or in a traditional way.

Effective Java enum class

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.