I've got the following class:
//GetHasCode, toString, and equalsTo removed to keep the question simple.
private String weaponName;
private String weaponType;
private int weaponDamage;
public WeaponObject(String name, String type, int damage)
{
this.weaponName = name;
this.weaponType = type;
this.weaponDamage = damage;
}
@Override
public int compareTo(WeaponObject compare) {
int name = this.getWeaponName().compareTo(compare.getWeaponName());
int type = this.getWeaponType().compareTo(compare.getWeaponType());
int damage = Integer.compare(this.weaponDamage, compare.getWeaponDamage());
if(name !=0 )
{
return name;
}
if(type != 0)
{
return type;
}
if(damage != 0)
{
return damage;
}
return 0;
}
SubClass:
public class Sword extends WeaponObject {
private String swordAttahment;
public Sword(String name, String type, int damage, String attachment) {
super(name, type, damage);
this.swordAttahment = attachment;
}
public String getSwordAttahment() {
return swordAttahment;
}
@Override
public int compareTo (WeaponObject compare)
{
int superCompare = super.compareTo(compare);
if(superCompare != 0)
{
return superCompare;
}
Sword other = (Sword)compare;
int attach = this.getSwordAttahment().compareTo(other.getSwordAttahment());
if(attach != 0)
{
return attach;
}
return 0;
}
Questions:
Given that I have a Sword
class
thatextends
WeaponObject, have I correctly implemented mycompareTo
in the Sword class?If the above isn't correct, then how would I correctly implement the
compareTo
method in my subclass?
WeaponObject doesn't have
getSwordAttahment()
method. So you can not make a comparison based onswordAttahment
. You can useinstanceof
to avoidClassCastException