Cannot cast class A to class B
java, oop
Solution
Have the `GameCharacter` interface define a `getLevel()` method which `Monster` and `Player` both implement.
public interface GameCharacter
{
public int getLevel( );
}
Once you've done that, you're taking advantage of polymorphism and don't even need to cast.
Also, do you really mean to cast `this` which is of type `Player`, to type `Monster`? Or do you mean:
public void performAttackOn(GameCharacter who)
{
for (int i =0 ; i < who.getLevel( ) ; i++)
{
// do stuff...
}
}
Problem
What is the proper way to access the field `level` from instance of `Minotaur`? Getting error in `for (int i =0 ; i < ((Monster) this).level ; i++)` which is `Cannot cast from Player to Monster`. ``` package player; import monsters.*; public class Player extends GameCharacter { public void performAttackOn(GameCharacter who){ if (who instanceof Monster ){ for (int i =0 ; i < ((Monster) this).level ; i++) { // << } public static class Minotaur extends Monster{ // << nested class which is being created and there is need to access it's level public Minotaur () { type = "Minotaur"; } } } ``` ``` package monsters; public class Monster extends GameCharacter{ public int level = 1; } ``` ``` package monsters; public abstract class GameCharacter{ public static class Minotaur extends Monster{ public Minotaur(){ type = "Minotaur"; hitPoints = 30; weapon = new Weapon.Sword(); } } } ``` `Minotaur` should extend `monsters.GameCharacter`, `monsters.Monster` and override in `Player.player` some methods which was inherited from `monsters.GameCharacter`