Lawrence Lelo Lawrence Lelo - 5 months ago 13
Java Question

Why is "instanceof" not working?

I'm using the Java instanceof but it doesn't seem to be working.

I have three java classes that extend a Hero class.

The Hero.java class:

public abstract class Hero {

protected int health;

public Hero() {
}
}


The other three classes:

public class Archer extends Hero {
public Archer() {
}
}

public class Mage extends Hero {
public Mage() {
}
}

public class Warrior extends Hero {
public Warrior() {
}
}


I have this main class WelcomeScreen.java

public class WelcomeScreen {

private Archer archer;
private Mage mage;
private Warrior warrior;
private Hero hero;

public WelcomeScreen() {

// choose a hero (archer/mage/warrior)
hero = archer;
new Game(hero);
}

public static void main(String args[]) {
new WelcomeScreen();
}

}


that instantiates the Game.java class

public class Game {

public Game(Hero chosenHero) {

if (chosenHero instanceof Mage) {
System.out.println("you selected mage");
} else if (chosenHero instanceof Archer) {
System.out.println("you selected archer");
} else if (chosenHero instanceof Warrior) {
System.out.println("you selected warrior");
} else {
System.out.println("you selected NOTHING");
}
}

}


In Game.java, the code is meant to check whether chosenHero is an object of Archer.java, Warrior.java, or Mage.java, but I result with "you selected NOTHING". Why does instanceof fail to check if I already assigned it to Archer.java in the WelcomeScreen?

Answer

Because your constants are null. When you say,

private Archer archer;

it is equivalent to

private Archer archer = null;

Additionally, you have created three fields per instance. I think you wanted to do something like

private static final Hero archer = new Archer();
private static final Hero mage = new Mage();
private static final Hero warrior = new Warrior();

See also What does it mean to “program to an interface”?