A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 付维翔 中级黑马   /  2012-10-25 17:43  /  1358 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在以下Adjustable接口和Base类都定义了adjust()方法,这两个方法的参数签名相同,但有着不同的功能。
  1. public interface Adjustable {
  2. // 调节温度
  3. public void adjust(int temperature);
  4. }
  5. public class Base {
  6. private int speed;

  7. // 调节速度
  8. public void adjust(int speed) {
  9. this.speed = speed;
  10. }
  11. }
复制代码
如果有一个Sub类同时具有调节温度和调节速度的功能,那么Sub类需要继承Base类,并且实现Adjustable接口,但是以下代码不能满足

  1. public class Sub extends Base implements Adjustable {
  2. public int temperature;

  3. public void adjust(int temperature) {
  4. this.temperature = temperature;
  5. }

  6. }
复制代码
以上Sub类实现了Adjustable接口,并且把Base()类中的方法覆盖了,这意思味着失去调节速度的功能。求如何解决

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

2 个回复

倒序浏览
我觉得可以用组合规避这个问题
  1. class Sub implements Adjustable {
  2.         public int temperature;
  3.         private Base b = new Base();
  4.         public void adjust(int temperature) {
  5.                 this.temperature = temperature;
  6.         }
  7. }
复制代码
或者内部类

  1. class Sub2 extends Base{
  2.         class AdjustModule implements Adjustable{
  3.                 public void adjust(int temperature) {}
  4.         }
  5. }
复制代码
回复 使用道具 举报
官仁杰 发表于 2012-10-25 18:24
我觉得可以用组合规避这个问题或者内部类

谢谢,问题解决
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马