本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
Q: I see that some Java library classes define some final constants. By curiosity, I printed out some of these final constants using "System.out.println(...)". I observed that most of these constants are just simple numbers such 0, 1, 2. Why other to define them?
A: If you use 0, 1 , 2 ... directly in the code, you may forget what they mean in a few days. In addition, the same number can stand for different things in a different contexts.
Hence, people usuall call these numbers "magic numbers". Remember this world, it will help to talk Java as a native Canadian does.
Ia a real project, it is a common practice to define an interface to hold all the final constants.
For instance, if you buikd a Web site using Java servlet and JSP, you can define an interface called PageNames to collect all the page names. By doing so, you can avoid hard-code pages in your source files so that they can be easily maintained. In a job interview, I have been asked: Where is the good place to define constants for a project?
更多精彩文章及讨论，请光临枫下论坛. 网址: rolia.net/zh
This post has been archived. It cannot be replied.