3. 接口持有多个类的共享常量 (视频下载) (全部书籍)
接口另一主要功能, 马克 - to-win: 可以使用接口来引入多个类的共享常量. 所有的这些变量名都将作为常量看待. 所有定义在接口中的常量都默认为 public,static 和 final. 原因见后面.
下面的例子当中, 如果 Server 回答的结果是 0 或 1, 程序可读性太差, 效果绝对没有 YES 或 NO 好. 所以就把 YES 和 NO 放到了 Client 和 Server 的共同的接口 ConstantbaseM_to_win 当中.
note: the following example class Client and Server use the constants like NO and Yes at the same time, so, they define the constants in the interface of ConstantbaseM_to_win.
例 1.3:
- interface ConstantbaseM_to_win {
- static int NO = 0;
- int YES = 1;
- }
- class Server implements ConstantbaseM_to_win {
- int answer() {
- // 通过其他渠道知道, 今天不下雨
- return NO;
- }
- }
- class Client implements ConstantbaseM_to_win {
- static void ask(int result) {
- switch (result) {
- case NO:
- System.out.println("不下雨");
- break;
- case YES:
- System.out.println("下雨");
- break;
- }
- }
- }
- public class Test {
- public static void main(String args[]) {
- Client c = new Client();
- .................
详情请进:
来源: http://www.bubuko.com/infodetail-2779270.html