Can anybody help me to solve the problem which is about the "super" in Java?
The "super" part I'm not very clear in Java, so how can I code it?
public class AggressiveAlien extends Alien
{
public AggressiveAlien(XYCoordination currentLocation, int energyCanister)
{
super(currentLocation,开发者_如何学Go energyCanister);
}
public int collectCanister(NormalPlanet canister)
{
super.collectCanister(canister);
n=1;
}
private boolean attack(int lifePoints)
{
boolean attack;
if (AggresiveAlien.currentLocation() = Alien.getOtherAlien())
{
AggresiveAlien.energyCanisters = (int) (1/2) * Alien.energyCanisters + AggresiveAlien.energyCanisters;
lifePoints = lifePoints - 1;
attack = true;
}
return attack;
}
}
What you have written is correct, provided that the Alien
class has a constructor with the signature:
public Alien(XYCoordination, int)
Specifically,
super(currentLocation, energyCanister);
means, before you run this constructor run the constructor for the immediate superclass passing it the currentLocation
and energyCanister
values. Note that every constructor (apart for the Object
constructor) chains to a superclass constructor, either explicitly or implicitly.
However, the following is probably incorrect:
AggresiveAlien.currentLocation()
That requires currentLocation()
to be a static method, and that would imply that all instances of a AggresiveAlien
have the same location ... which doesn't make a lot of sense. In fact, I think the method needs to be an instance method, and the call would therefore have to be:
this.currentLocation()
or just
currentLocation()
You have made this mistake in a number of places.
It means "call the version of this method (or constructor) that's defined in the immediate superclass".
精彩评论