免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1489 | 回复: 4
打印 上一主题 下一主题

[请教] constants define in java package !!! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2004-01-05 08:55 |只看该作者 |倒序浏览
Hi, All

Have a question about java.

  1. How do you usually define constants with a package?

  2. The only solution I can find is to define an "Constants Interface" like this:
  3. interface Constants
  4. {
  5.    static final public int SUCCESS=1;
  6.    static final public int FIAL=0;
  7.    ... ...
  8. }
  9. Then, every class in the package  using these constants has to implement this interface.

  10. An abstract final class defining these constants is an alternative, but then I have to site the class name when using the constants, like this:
  11. if( dosth()==Constant.SUCCESS)
  12. {... ...}

  13. I'm wondering if there is any other better solutions to define package constants?  You know, Im some kind of new comer to java but am involved in a java project now.
复制代码

论坛徽章:
0
2 [报告]
发表于 2004-01-05 16:08 |只看该作者

[请教] constants define in java package !!!

Should be OK. Actually tomcat's javax.servlet.* implementation is doing exactly that. Take a look at jakarta-tomcat-5.0.16-src/src/jakarta-servletapi-5/jsr154/src/share/javax/servlet/http/HttpServletResponse.java , the http status codes are all defined that way.

Beware that those are defined in a specific interface (in the above case, the HttpServletResponse interface), not in a global Constant interface. But I think where to define the constants really depends on the actual situation.

论坛徽章:
0
3 [报告]
发表于 2004-01-05 16:47 |只看该作者

[请教] constants define in java package !!!

Thank you for your reply

论坛徽章:
0
4 [报告]
发表于 2004-01-05 18:27 |只看该作者

[请教] constants define in java package !!!

In the forth coming Java 1.5, there will be an exciting feature, static import. You may take a look at it.

http://java.sun.com/features/2003/05/bloch_qa.html

论坛徽章:
0
5 [报告]
发表于 2004-01-05 18:29 |只看该作者

[请教] constants define in java package !!!

The static import facility offers a clean alternative. It lets the programmer avoid qualifying static member names without subtyping. It's analogous to the package import facility, except that it imports static members from a class, rather than classes from a package. Here's how it looks:

  1. import static org.iso.Physics.*;

  2. class Guacamole {
  3.     public static void main(String[] args) {
  4.         double molecules = AVOGADROS_NUMBER * moles;
  5.         ...
  6.     }
  7. }
复制代码




Note that this works whether Physics is an interface or a class. If it just defines constants, it should definitely be a class rather than an interface.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP