随笔-348  评论-598  文章-0  trackbacks-0
请看下面两段代码
interface Name extends Comparable {
  
public int compareTo(Object o);
}


class SimpleName implements Name {
  
private String base;
  
public SimpleName(String base) {
    
this.base = base;
  }

  
public int compareTo(Object o) {
    
return base.compareTo(((SimpleName)o).base);
  }

}


class ExtendedName extends SimpleName {
  
private String ext;
  
public ExtendedName(String base, String ext) {
    
super(base); this.ext = ext;
  }

  
public int compareTo(Object o) {
    
int c = super.compareTo(o);
    
if (c == 0 && o instanceof ExtendedName)
      
return ext.compareTo(((ExtendedName)o).ext);
    
else
      
return c;
  }

}


class Client {
  
public static void main(String[] args) {
    Name m 
= new ExtendedName("a","b");
    Name n 
= new ExtendedName("a","c");
    
assert m.compareTo(n) < 0;
  }

}



interface Name extends Comparable<Name> {
  
public int compareTo(Name o);
}


class SimpleName implements Name {
  
private String base;
  
public SimpleName(String base) {
    
this.base = base;
  }

  
public int compareTo(Name o) {
    
return base.compareTo(((SimpleName)o).base);
  }

}


// use legacy class file for ExtendedName

class Test {
  
public static void main(String[] args) {
    Name m 
= new ExtendedName("a","b");
    Name n 
= new ExtendedName("a","c");
    
assert m.compareTo(n) == 0;  // answer is now different!
  }

}



注意到不一样的地方呢吗?compareTo方法的参数不一样。上面的代码在调用m.compareTo(n)的时候会调用ExtendedName中的,而下面这种不会,因为ExtendedName中的compareTo参数是Object,相当于重载了compareTo的方法,而父类SimpleName中的compareTo方法由于参数不同仍然被保留了,所以将Name类型的参数传给compareTo的时候会优先调用SimpleName中的compareTo(Name)来进行比较。
所以在一些继承里面,建议使用Object做参数的类型,称之为Binary Compatibility。

---------------------------------------------------------
专注移动开发

Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2007-10-28 21:09 TiGERTiAN 阅读(906) 评论(2)  编辑  收藏 所属分类: Java

评论:
# re: Java Generics And Collection 学习笔记(1)[未登录] 2007-10-29 16:45 | 刘明
没明白。

首先,你的第二个的ExtendedName没写。这是我写的,看是不是合你的意思。
public class ExtendedName extends SimpleName {
private String ext;

public ExtendedName(String base, String ext) {
super(base);
this.ext = ext;
}

public int compareTo(Name o) {
int c = super.compareTo(o);
if (c == 0 && o instanceof ExtendedName) {
return ext.compareTo(((ExtendedName)o).ext);
} else {
return c;
}
}
}

如果你的ExtendedName和我的一样的话,两个client返回的结果是一致的。-1。例如assert的话,第二个应该也是'<'。不知道是我跟你写的ExtendedName不一致造成的,还是其它什么问题。大家研究研究。。。  回复  更多评论
  
# re: Java Generics And Collection 学习笔记(1) 2007-10-29 17:30 | TiGERTiAN
上面不是有注释吗,ExtendedName和第一个一样就是传入的参数是Object不是Name,如果传入的参数是Name那么结果就一样了,但是如果SimpleName中传入了Name类型,而ExtendedName中传入了Object类型则结果是不一样的。下面那个就是相等了。  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: