java中接口interface可以持有多个类的共享常量
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();
Server s = new Server();
c.ask(s.answer());
}
}
更多内容请见原文,原文转载自:https://blog.csdn.net/qq_44639795/article/details/103110986
最新文章
- ASP.NET Global.asax详解
- Leetcode 26 Remove Duplicates from Sorted Array STL
- 七、CCScene
- Orchard工作原理
- VBScript 函数
- 用phpQuery像jquery一样解析html代码
- Java并发编程--Fork/Join框架使用
- (简单) POJ 1062 昂贵的聘礼,Dijkstra。
- Java中的增强 for 循环 foreach
- 老男孩Python全栈开发(92天全)视频教程 自学笔记18
- LogHelper 日志记录帮助类
- 深入了解GOT,PLT和动态链接
- WebApi设置HttpContext.Current.User
- Integer 比较忽略的问题
- JavaScript -- 时光流逝(二):js中数组的方法
- day_1 Python介绍及计算机组成和系统
- Puppet报错汇总
- centos7开放及查看端口
- Cracking The Coding Interview5.1
- IOS 将公历日期转换为中国农历