正在加载图片...
Thinking in Java 3 Edition //: c08: Months. java // Using interfaces to create groups of constant package c08; public interface Months i JANUARY = 1, FEBRUARY =2, MARCH =3, APRIL 4, MAY = 5, JUNE JULY AUGUST =8, SEPTEMBER =9, OCTOBER =10 NOVEMBER =11, DECEMBER =12; }///: 注意一下,Java的编程风格是,用全部大写字母(用下划线分隔同一个标 识符里的各个单词)来表示,用常量进行初始化的 static fina变量 nterface的数据成员自动就是 public的,因此就不必再注明了。 你可以像对待别的 package那样,用 import c08*或者 c08 Months把它引进来,这样就能在这个 package的外面用 Months JANUARY之类的表达式来使用这些常量了。当然,你得到的 是一个int,因此它没有像C++的enum那样的类型安全,但是这种 (很常见的)手法要比直接在程序里面用数字要好得多。(这种方法通常被 成为使用“神奇数字”,并且使得代码的维护变得非常困难。) 如果你确实需要额外的类型安全,可以像这样创建一个类:③3 // A more robust enumeration system public final class Month t t() private string name; private Month(String nm) name nm; 1 public string tostring( return name public static final Month JAN new Month("January ") FEB new Month("February") MAR new Month("March"), nth(Al AY new Month("May") JUN new Month("June " JUL Month("July " AUG new Month("August " SEP new Month("September") OCT new Month("October") NOV nth("November") DEC new Month("December )i public static final Month[] month = t JAN, FEB, MAR, APR, MAY, JUN, 第10页共47页 www.wgqqh.com/shhgs/tij.htmlThinking in Java 3 rd Edition www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com ✄ 10 ☎ ✆ 47 ☎ //: c08:Months.java // Using interfaces to create groups of constants. package c08; public interface Months { int JANUARY = 1, FEBRUARY = 2, MARCH = 3, APRIL = 4, MAY = 5, JUNE = 6, JULY = 7, AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, NOVEMBER = 11, DECEMBER = 12; } ///:~ ¹3Ž Java (áâòè ˆc«¾ó(ˆŽôõñ‡3×ö ÷øË(Ñ×H³ )Q?‘ ˆ·Û]}f`( static finalÛ interface  public    ¡ÝE}¥ù¨( package Y¦ ˆ import c08. * 3š c08. M on th s PAú]Q ¦;F × package (½¶ˆ M on th s. JAN UARY u(?û´Qçˆ Ì·Û, Ÿ ¡‰g( 3× in t æòAœm} C+ + ( en um Y¦(hüc  † (Š· ()C%8ÒFâ%˶ˆc¾%‘‰V( †µ·v Ž™çˆÍýþc¾Ï ž³ç‰K€(‰¯·U) ÄÅ¡Ìñî%½(hüc ÝE} ¦123×L ✝ ✞ ✞ ✟ //: c08:Month.java // A more robust enumeration system. package c08; import com.bruceeckel.simpletest.*; public final class Month { private static Test monitor = new Test(); private String name; private Month(String nm) { name = nm; } public String toString() { return name; } public static final Month JAN = new Month("January"), FEB = new Month("February"), MAR = new Month("March"), APR = new Month("April"), MAY = new Month("May"), JUN = new Month("June"), JUL = new Month("July"), AUG = new Month("August"), SEP = new Month("September"), OCT = new Month("October"), NOV = new Month("November"), DEC = new Month("December"); public static final Month[] month = { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有