Error trying to pass object in argument of its own method

3255 views java
2

I have a class "Character" that contains an ArrayList of "State" object. These state objects have a method trigger(Character charac) that needs to use the character object they are stocked in :

public abstract class State {
    private int turns;
    public void trigger(Character charac){
        action(charac);
        turns--;
    }
    public abstract void action(Character charac);
}

When i try to use "this" as argument (look in triggerStates method below), netbeans tells me "incompatible types: projet.m1s1.Character cannot be converted to java.lang.Character"

public class Character extends Living{

    private ArrayList states;

    public Character(String name,int life, int mana, int strengh, int intelligence, int armor){
        super(name,life,mana,strengh,intelligence,armor);
        states = new ArrayList();
    }

    public void triggerStates(){
        for(int i=0 ; i<states.size() ; i++){
            try{
                State sta = (State)states.get(i);
                sta.trigger(this);
            }
            catch (ClassCastException e){
                System.out.println("ClassCastException in Character.TriggerStates");
            }
        }
    }

}

Hope i made myself clear and didn't ask a frequently asked question.

Thanks in advance for your answers !

answered question

Don't name your class Character. You would have to fully qualify it every time, because java.lang.Character has precedence.

why dont you change your character class' name. For example MyCharacter. Because Character is a class in java.lang package.

2 Answers

3

You have imported the wrong class in your imports. You have imported java.lang.Character while you should be importing projet.m1s1.Character.

When running your code locally I get no issues this way.

posted this
2

Finally managed to make it work, these two class were in separate packages and i just needed to import "import projet.m1s1.Character;" in State class

posted this

Have an answer?

JD

Please login first before posting an answer.