Issue
I have an ArrayList which contains different types of enemies as objects, all of these objects inherit a general 'Attackers' abstract class. I want the 'Archer' enemy to create a projectile object at random intervals, however, launching projectiles should only apply to the archer enemy type and not the fighter type, its relevant method is not included in the abstract class and is instead a method exclusive to the Archer subclass. Essentially I am trying to run a loop in the draw function to check if the object in the ArrayList index contains an object of type Archer, and if it does run a random number to determine whether the specified object shoots.
void draw() {
for(Attacker a: attackers) {
//I want to make a check here to see if the object in the specified index is of object type Archer, and run the boolean return in the Archer subclass if it is
if (a.shoot() == true)
arrows.add(new Arrow(etcetc.))
}
}
the Attacker superclass looks like this:
abstract class Attacker {
float x;
float y;
Attacker(float x, float y)
{
this.x = x;
this.y = y;
}
void update() {
move();
display();
}
abstract void display();
abstract void move();
}
and the archer subclass looks like this:
class Archer extends Attacker {
Archer(float x, float y) {
super(x,y);
}
void move()
void display()
//I am trying to call this method, but only if the Attacker object is an Archer
boolean shoot() {
...
}
}
I'm not sure how to go about getting the boolean to only run when the object is an archer, but trying to isolate the ArrayList to object type is the approach that makes the most sense to me which I cannot figure out to do. Any help would be greatly appreciated.
Solution
You might be looking for the instanceof operator in Java.
Essentially obj instanceof Archer will only be true if obj is an Archer.
More details: https://www.geeksforgeeks.org/instanceof-keyword-in-java/
Answered By - MAK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.