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

2012/12/31

How to use method from another class?

MindlessRicky MindlessRicky

2012/12/31

#
So I have this class called zwarteBalk:
import greenfoot.*; 

public class zwarteBalk extends Actor
{

    public void act() 
    {
        checkKeys(7);
    }    
    
    
    
    public void checkKeys(int speed)
    {
        
        if(Greenfoot.isKeyDown("right"))
        {
            setLocation(getX()-speed,getY());
        }
        
        if(Greenfoot.isKeyDown("left"))
        {
            setLocation(getX()+speed,getY());
        }
    }
    
}
And in the class below named GravityUp, I try to use the method checkKeys() from zwarteBalk with
zwarteBalk balk = new zwarteBalk();
         balk.checkKeys(7);
import greenfoot.*;

public class GravityUp extends Actor
{
  

    public void act() 
    {
         zwarteBalk balk = new zwarteBalk();
         balk.checkKeys(7);
    }    
}
It doesn't work.. What am I doing wrong?
danpost danpost

2012/12/31

#
The problem is that line 9 in 'GravityUp' class is creating a new 'zwarteBalk' object which is not added to the world before calling 'checkKeys' on it; which should cause an 'illegalStateException' error. Besides that, after the method call on the 'new' object, the whole thing (the new object and anything done to it) will be lost at the end of the 'act' method. Each cycle, the 'act' method in 'zwarteBalk' class will run on all objects of that class; so, why would it be neccessary to call it from another class? If you want to have the method run on all objects of the 'zwarteBalk' class that are in the world again from the other class, use:
for(Object obj: getWorld().getObjects(zwarteBalk.class))
{
    zwarteBalk balk = (zwarteBalk) obj;
    balk.checkKeys(7);
}
MindlessRicky MindlessRicky

2012/12/31

#
Thanks for the reply! The thing is I want all the objects of the GravityUp class to do this:
if(Greenfoot.isKeyDown("right"))  
        {  
            setLocation(getX()-speed,getY());  
        }  

        if(Greenfoot.isKeyDown("left"))  
        {  
            setLocation(getX()+speed,getY());  
        }  
, without typing it all out in the GravityUp class itself and just take it from another class. Sorry for not being clear enough.
danpost danpost

2012/12/31

#
Unfortunately, you cannot run a method in one class on an object of another class (unless it is a sub-class of the class with the method).
MindlessRicky MindlessRicky

2012/12/31

#
:( And what if it was a subclass?
danpost danpost

2012/12/31

#
As long as the method is in a shared superclass, they both can use it (without having to copy the code).
You need to login to post a reply.