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

2018/4/16

Having trouble with finding a method from another subclass and calling it

Dabigbluebass Dabigbluebass

2018/4/16

#
Im relatively new to greenfoot but I think i have the basics of it down. It is spring break and I am just doing this for a bit of fun but I cannot seem to be able to call a method from another subclass of my code.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class killer here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public abstract class Killer extends Actor
{
    public abstract void act();

    public void kill() 
    {
        Actor test = getOneIntersectingObject(Dude.class); // place the class you want to check for, instead of null write "yourclass.class" without "".
        if( test == null){
        }else{
            test.[u]wither[/u]();
        }

    }
}    
I am having trouble call the wither() method. It is defined it the dude subclass:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class dude here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public abstract class Dude extends Actor
{
    private int lives;
    public Dude(){
       lives = 3;
    }

    public abstract void act();
    
    public void regen(int x){
        lives += x;
    }
    
    public void wither(){
        lives --;
    }
    
    public int getLives(){
        return lives;
    }

}
I don't know what to do
danpost danpost

2018/4/16

#
In line 15, you have test as an Actor object reference. However, you want the method wither in the Dude class to be executed. You must specify that wither is a Dude type object for the search for the method to include looking in the Dude class. You could change line 15 to the following:
Dude test = (Dude)getOneIntersectingObject(Dude.class);
or as an alternative, you could change line 18 the this:
((Dude)test).wither();
Dabigbluebass Dabigbluebass

2018/4/16

#
Thanks a lot, works great now
You need to login to post a reply.