About final constants in Java library classes

system (_)
<本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f >
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?
<本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f >

2000-9-4 -04:00

回到话题: Java Q&A (2) (compiled by jabber)

回到论坛: HOME枫下论坛枫下论坛主坛工作学习IT技术讨论