Lawrence Lelo Lawrence Lelo - 2 years ago 89
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 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

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 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, the code is meant to check whether chosenHero is an object of,, or, but I result with "you selected NOTHING". Why does instanceof fail to check if I already assigned it to in the WelcomeScreen?

Answer Source

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”?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download