正在加载图片...
Thinking in Java 3 Edition 接口所定义的数据都自动是 static和 final的。它们不能是“空白的 fina数据成员”,但是可以用非常量的表达式来对它们进行初始化。例 如: // c08: Randvals java // Initializing interface fields with / non-constant initializers import java. util.* public interface Randvals t Random rand new Random(i int randomInt rand. nextInt (10) long randomLong rand. nextLong()*10; float random loat rand. nextLong()*10; 由于数据成员都是 static的,因此装载类的时候,也就是第一次访问这 些数据成员的时候进行初始化。下面就是一个简单的测试: public class TestRandvals t() System. out. println(Randvals randomInt)i System. out. println(Randvals. randomLong)i System. out. println(Randvals. randomFloat) System. out. println(Randvals. randomDouble)i monitor. expect(new String[] t 号各-2\1d+m 号各-?\\d+ 号各-2d\\.\d+E?-?\\d+m 号各-?\\d\\,\d+E?-?\\d+m }) }///: 当然,这些数据都不算是接口的组成部分,相反它们保存在这个接口的静 态存储区内。 接口的嵌套 接口既可以嵌套在类里,也可以嵌套在接口里面。34这一点揭示了许多 非常有趣的特点 //: c08: nesting: NestingInterfaces java package co8.nesting 第12页共47页 www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.comThinking in Java 3 rd Edition www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com ✄ 12 ☎ ✆ 47 ☎ DO4(cmÆý  static  final(AX;́( finalcmŽ&Ï ÝEˆ¯·Û(?û´Q¥A]}f` ÄL //: c08:RandVals.java // Initializing interface fields with // non-constant initializers. import java.util.*; public interface RandVals { Random rand = new Random(); int randomInt = rand.nextInt(10); long randomLong = rand.nextLong() * 10; float randomFloat = rand.nextLong() * 10; double randomDouble = rand.nextDouble() * 10; } ///:~ 7)cmŽ&Æ static ( æòä(M [3¨™š ÌcmŽ&(M]}f`Ž¶3×GH(L //: c08:TestRandVals.java import com.bruceeckel.simpletest.*; public class TestRandVals { private static Test monitor = new Test(); public static void main(String[] args) { System.out.println(RandVals.randomInt); System.out.println(RandVals.randomLong); System.out.println(RandVals.randomFloat); System.out.println(RandVals.randomDouble); monitor.expect(new String[] { "%% -?\\d+", "%% -?\\d+", "%% -?\\d\\.\\d+E?-?\\d+", "%% -?\\d\\.\\d+E?-?\\d+" }); } } ///:~ Ÿ ÌcmÆX(Ž >A€F ×( €  ²ÝEFË [ÝEF˶ ✝ ✞✠✡✟ 3C‘,V ¯·m ()CL //: c08:nesting:NestingInterfaces.java package c08.nesting;
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有