本帖最后由 张锐 于 2012-3-13 19:38 编辑
写了个程序验证了下:main函数和父类是这样的:- package test;
- import java.util.Collection;
- import java.util.TreeSet;
- import myutil.SOP;
- public class Lianxi {
- public static void main(String[] args)
- {
- Collection<Fu> c = new TreeSet<Fu>();
- c.add(new Fu("aa"));
- c.add(new Fu("bb"));
- c.add(new Fu("cc"));
- c.add(new Zi("aba",10));
- c.add(new Zi("ccb",20));
- SOP.sop(c);
-
- }
- }
- class Fu implements Comparable<Fu> {
- String name;
- Fu(String name){
- this.name = name;
- }
- public int compareTo(Fu o) {
- // TODO Auto-generated method stub
- SOP.sop("fu compare "+this.name+"..."+o.name);
- return this.name.compareTo(o.name);
- }
- }
复制代码 子类分为不同的情况试试。
第一种情况:- class Zi extends Fu{
- int age;
- Zi(String name,int age) {
- super(name);
- this.age = age;
- // TODO Auto-generated constructor stub
- }
- public int compareTo(Fu o) {
- // TODO Auto-generated method stub
- SOP.sop("zi compare "+this.name+"..."+o.name);
- return this.name.compareTo(o.name);
- // return new Integer(this.age).compareTo(new Integer(z.age));
- }
-
-
- }
复制代码 这时候的输出结果是:
fu compare bb...aa
fu compare cc...aa
fu compare cc...bb
zi compare aba...bb
zi compare aba...aa
zi compare ccb...bb
zi compare ccb...cc
[aa, aba, bb, cc, ccb]
第二种子类的情况:- class Zi extends Fu{
- int age;
- Zi(String name,int age) {
- super(name);
- this.age = age;
- // TODO Auto-generated constructor stub
- }
- public int compareTo(Zi o) {
- // TODO Auto-generated method stub
- SOP.sop("zi compare "+this.name+"..."+o.name);
- // return this.name.compareTo(o.name);
- return new Integer(this.age).compareTo(new Integer(o.age));
- }
-
-
- }
复制代码 这时候的输出结果是:
fu compare bb...aa
fu compare cc...aa
fu compare cc...bb
fu compare aba...bb
fu compare aba...aa
fu compare ccb...bb
fu compare ccb...cc
[aa, aba, bb, cc, ccb]
所以根据我的理解,结论是:
子类和父类比较的时候,
如果子类可以实现和父类的“交叉”比较,则调用子类的比较方法。
如果子类不可以实现和父类的“交叉”比较,就直接调用父类的比较,这时候因为多态的存在,父类是肯定可以实现和子类的比较出结果的。
|