读 practical java 中文版时 实践13:调用super.equals()以唤起b a se cla s s的相关行为.有个例子不是很明白.public class MyGolfball extends Golfball
{
public final static byte TwoPiece = 0;
public final static byte ThreePiece = 1;
private byte ballConstruction; public MyGolfball(String str, String mk,
int comp, byte construction)
{
super(str, mk, comp);
ballConstruction = construction;
} public byte construction()
{
return ballConstruction;
} public boolean equals(Object obj)
{
if (this == obj) //1
return true; if (obj != null && getClass() == obj.getClass() && //2
super.equals(obj)) //此处比较两个对象的超类是否相同,可super是Golfball类,obj 是MyGolfball,调用Golfball的equals方法:Golfball gb = (Golfball)obj;obj 不就是要向下转化为Golfball类么?不久会出问题? {
MyGolfball gb = (MyGolfball)obj; //Classes equal, downcast.
if (ballConstruction == gb.construction()) //Compare attrs.
return true;
}
return false;
}
}class Golfball
{
private String brand;
private String make;
private int compression; public Golfball (String str, String mk, int comp)
{
brand = str;
make = mk;
compression = comp;
} public String brand()
{
return brand;
} public String make()
{
return make;
} public int compression()
{
return compression;
} public boolean equals(Object obj)
{
if (this == obj)
return true; if ((obj != null) && (getClass() == obj.getClass()))
{
Golfball gb = (Golfball)obj;
if ((brand.equals(gb.brand())) &&
(make.equals(gb.make())) &&
(compression == gb.compression()))
{
return true;
}
}
return false;
}}问题在MyGolfball equals方法处,有人帮小弟解释一下
{
public final static byte TwoPiece = 0;
public final static byte ThreePiece = 1;
private byte ballConstruction; public MyGolfball(String str, String mk,
int comp, byte construction)
{
super(str, mk, comp);
ballConstruction = construction;
} public byte construction()
{
return ballConstruction;
} public boolean equals(Object obj)
{
if (this == obj) //1
return true; if (obj != null && getClass() == obj.getClass() && //2
super.equals(obj)) //此处比较两个对象的超类是否相同,可super是Golfball类,obj 是MyGolfball,调用Golfball的equals方法:Golfball gb = (Golfball)obj;obj 不就是要向下转化为Golfball类么?不久会出问题? {
MyGolfball gb = (MyGolfball)obj; //Classes equal, downcast.
if (ballConstruction == gb.construction()) //Compare attrs.
return true;
}
return false;
}
}class Golfball
{
private String brand;
private String make;
private int compression; public Golfball (String str, String mk, int comp)
{
brand = str;
make = mk;
compression = comp;
} public String brand()
{
return brand;
} public String make()
{
return make;
} public int compression()
{
return compression;
} public boolean equals(Object obj)
{
if (this == obj)
return true; if ((obj != null) && (getClass() == obj.getClass()))
{
Golfball gb = (Golfball)obj;
if ((brand.equals(gb.brand())) &&
(make.equals(gb.make())) &&
(compression == gb.compression()))
{
return true;
}
}
return false;
}}问题在MyGolfball equals方法处,有人帮小弟解释一下
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货