How can I use the parent class to get a parameter from child class?
I have this child class AggressiveAlien and here is one method inside it
public boolean attack()
{
boolean attack;
if (currentLocation == this.AggresiveAlien.getCurrentLocation)
{
energyCanister = (int) ( (1/2) * alien2.energyCanister + energyCanister);
lifePoints = (int) (lifePoints - (1/2)*alien2.energyCanister);
attack = true;
}
return attack;
}
I would like the returned value to be used in the parent class Alien
public void gotAttacked()
{
if (AggresiveAlien.attack())
energyCanister = energyCanister/2;
}
But it seems to be giving errors on the AggresiveAlien.attack() part. Is there any way for me to use this returned value from AggresiveAlien to be used in Alien?
Help would be very much appreciated. Thanks!
Here is another part of the child class
public class AggressiveAlien extends Alien { public AggressiveAlien(XYCoordination currentLocation, int energyCanister) { super(currentL开发者_C百科ocation, energyCanister); }
public int collectCanister(NormalPlanet canister)
{
super.collectCanister();
n=1;
}
I think you might be having two problems... First you need to cast the base type to the child type, such as
((AggressiveAlien)this).attack()
Also, 1/2 may actually be 0! 1 and 2 are interpreted as integers which means the value of any division is floored! so 1/2 = (int) 0.5 = 0
check your types! You better use 0.5 or use /2.0 to force the value to compute as a float or double (depending on the platform).
Hope this helped!
It looks as though you're trying to use AggresiveAlien statically. Instead you probably want to do:
if ((AggresiveAlien)this.attack()) energyCanister = energyCanister/2;
But I can't be sure given the limited amount of information.
you say, you have a parent and child class, which means you are using inheritance
here. you can easily accomplish your task by using virtual function and then overriding in the child class.
in your Alien
class create a function called attack()
and override in the child class AggresiveAlien
.
like following:
Alien class:
public boolean attack()
{
return false;
}
AggresiveAlien class:
public boolean attack()
{
return true;
}
and your gotAttacked function
public void gotAttacked()
{
if (this.attack())
energyCanister = energyCanister/2;
}
精彩评论