請看下面兩段代碼

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方法的參數(shù)不一樣。上面的代碼在調(diào)用m.compareTo(n)的時候會調(diào)用ExtendedName中的,而下面這種不會,因為ExtendedName中的compareTo參數(shù)是Object,相當(dāng)于重載了compareTo的方法,而父類SimpleName中的compareTo方法由于參數(shù)不同仍然被保留了,所以將Name類型的參數(shù)傳給compareTo的時候會優(yōu)先調(diào)用SimpleName中的compareTo(Name)來進(jìn)行比較。
所以在一些繼承里面,建議使用Object做參數(shù)的類型,稱之為Binary Compatibility。
---------------------------------------------------------
專注移動開發(fā)
Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2007-10-28 21:09
TiGERTiAN 閱讀(913)
評論(2) 編輯 收藏 所屬分類:
Java