When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to itmust be an instance of a class that implements the interface.

As an example, here is a method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable:

public Object findLargest(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}

By casting object1 to a Relatable type, it can invoke the isLargerThan method.

If you make a point of implementing Relatable in a wide variety of classes, the objects instantiated from any of those classes can be compared with the findLargest() method—provided that both objects are of the same class. Similarly, they can all be compared with the following methods:

public Object findSmallest(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) < 0)
return object1;
else
return object2;
} public boolean isEqual(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ( (obj1).isLargerThan(obj2) == 0)
return true;
else
return false;
}

These methods work for any "relatable" objects, no matter what their class inheritance is. When they implement Relatable, they can be of both their own class (or superclass) type and a Relatable type. This gives them some of the advantages of multiple inheritance, where they can have behavior from both a superclass and an interface.

最新文章

  1. BZOJ 1004 【HNOI2008】 Cards
  2. javascript数据结构与算法--链表
  3. Liunx面试题
  4. curl operate elasticsearch
  5. 打开Genesis设置单位为mm
  6. Blocked Process Report
  7. java网络---查找Internet
  8. 关于Apple设备私有的apple-touch-icon属性详解
  9. 字符串对比.net String.EndsWith方法 (String)
  10. Ctrl+Alt+T 文档大纲
  11. 利用Java提供的Observer接口和Observable类实现观察者模式
  12. mysql多个TimeStamp设置(转)
  13. win10 uwp 横向 AppBarButton
  14. Windows Server 2008 R2提示api-ms-win-crt-runtime-l1-1-0.dll 丢失解决方法
  15. .net基础学java系列(七)赶鸭子上架看项目代码
  16. sublime 学习笔记
  17. linux 下 mysql 常用命令
  18. ASP.NET MVC5+EF6+EasyUI 后台管理系统(91)-EF 连接 MySql
  19. 让你简洁清晰真正的了解什么是JavaSCript
  20. Python&amp;HDF5目录

热门文章

  1. LPHW-积累-ex1-6
  2. hdu 1874 畅通工程续
  3. 关于asp.net和iis的进程/线程问题,假如网站有1000个人访问,会产生多少个进程/线程啊
  4. Tornado服务器的学习
  5. FTP上传文件夹
  6. 单行bash、shell、perl命令
  7. 44.do文件格式
  8. PSPO表格
  9. “我爱淘”冲刺阶段Scrum站立会议3
  10. 文档对象模型(DOM)