Home > Software design >  class Monster cannot be cast to class Zombie (Monster and Zombie are in unnamed module of loader �
class Monster cannot be cast to class Zombie (Monster and Zombie are in unnamed module of loader �

Time:10-19

My code is configured like this:

public class Main {
    public static void main(String[] args) {
        Monster monster = new Monster();
        monster = (Zombie) monster;

    }
}

I have a class called Monster

public class Monster {

}

Another class Called Zombie that extends Monster

public class Zombie extends Monster{

}

When I run this from main -- I get the following error:

class Monster cannot be cast to class Zombie (Monster and Zombie are in unnamed module of loader 'app')

I apologize, but I've been trying to make sense of this, and I still don't understand. I only get the error in runtime. I was trying to follow this tutorial: https://www.geeksforgeeks.org/referencing-subclass-objects-subclass-vs-superclass-reference/

CodePudding user response:

it means you cannot turn the monster into a Zombie. Since Zombie is an extension of Monster, you would you something like this:

Monster monster = new Zombie();

does it work now?

  • Related