Java interface constant anti-pattern and how to define Java constants

Source: Internet
Author: User

Beginners Java people will inadvertently define the constants in the interface, the only reason is that the interface can not be instantiated, and the use of the interface defined by the constant is not attached to the instance. This is mainly the JDK itself gives us a lot of such examples, such as Java.io.ObjectStreamConstans, mostly appear before the Enum type arrives.

In fact, Java interface constants are an anti-pattern for the following reasons:

1. Interfaces cannot be prevented from being implemented or inherited, that is, a sub-interface or implementation is the definition of a constant that can be overridden so that a reference to a constant through the parent, subinterface (or implementation) can be inconsistent
2. Similarly, due to being implemented or inherited, a large number of interfaces, classes, or instances can be used to refer to the same constant in the inheritance tree, resulting in the constants defined in the interface polluting the namespace. (The Java compiler actually allows the use of instances to reference class variables)
3. The implication of an interface is that it needs to be implemented and represents a type whose public member is the API to be exposed. The constants defined in the interface are not the API

See also: Effective Java 19th: interface for defining types only

Since the interface is not suitable for defining constants, where is the constant home? Interfaces are built for implementation/inheritance, if placed in a class, and the class is final, and the construction method is closed. So our previous interface constants were defined

Read the full text


Java interface constant anti-pattern and how to define Java constants

Related Article

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.