This site requires JavaScript, please enable it in your browser!
Greenfoot back
Phiesel
Phiesel wrote ...

2014/7/6

'this' and NPE

Phiesel Phiesel

2014/7/6

#
I don't see the problem here. Maybe someone can explain. I'm playing around with inheritance, but some things are still hard to see. I have a World called 'Title' that creates 3 objects. 1) an object of class Start (so that the start-button can get pressed and do sth. ) 2) an object of class 'Quest' 3) an object of class 'Quest1' (that inherits from class 'Quest')
public class Title extends World
{
    Start start = new Start();
    Quest quest = new Quest();
    Quest1 quest1 = new Quest1();
    
    public Title()
    {    
        super(600, 400, 1); 
        prepare();
    }

    public void act()
    {
        if (Greenfoot.mouseClicked(start))
        {
            System.out.println("Started!");
            quest1.activateQuest();
        }
    }
    
    public void setQuest(Quest quest)
    {
        this.quest = quest;
    }

    private void prepare()
    {
        addObject(start, 297, 228);
    }
}
In 'Quest' is a method 'activateQuest'. 'Quest1' inherits this method. Goal was to make the object of 'Quest1' or 'Quest2,3,4...' the new 'Quest'-object in 'Title'.
public class Quest extends Actor
{
    public void activateQuest()
    {
        World myWorld = getWorld();
        Title title = (Title)myWorld;
        title.setQuest(this);
    }
}
During runtime I encounter a NullPointerException for line7 in 'Quest'. Is it a problem with 'this'? Or a problem with 'Quest1' being only a 'Quest'-object through inheritance?
danpost danpost

2014/7/6

#
Your 'quest1' object was never added into the 'title' world. In line 5 (Quest class), 'getWorld' will return a 'null' value. Line 7 tries to execute 'setQuest' on a non-existent world.
You need to login to post a reply.