请看下面两段代码

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 阅读(922) 
评论(2)  编辑  收藏  所属分类: 
Java