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

2014/1/3

Non Static Method?

Affan Affan

2014/1/3

#
I have this code
if(getWorld() != null)
        {
            if(canSee(Asteroid1.class))
            {
                if(Asteroid1.class != null)
                {
                    Asteroid1.createExplosion();
                    score = score+5;
                    destroyMultiple(Asteroid1.class);
                    createAsteroid1();
                }
            }
        }
It is inside a method inside a class called "Shot" Inside another class "Asteroid1" I have the method CreateExplosion:
 public void createExplosion()
    {      
        Explosion newExplosion = new Explosion();
        int x = getX();
        int y = getY();
        world.addObject(newExplosion, x, y);
    }
When I compile, I am told that "non-static method createExplosion" cannot be refferred to from a static context. What is wrong with my code? thanks.
shrucis1 shrucis1

2014/1/3

#
Is the first piece of code you gave us in a static method? If it is, then it needs to be in a non-static one. The reason you can't reference non-static methods from a static context is if you're doing something like Generic.getHighscore() (static) and there is no object of Generic, it couldn't call a non-static method, and even if it could, there wouldn't be any way to determine which object to call the non-static method of. If you're using objects and their methods, I would stick to using non-static methods, but if it's a class that provides extra methods for use by any class, and is not meant to be instantiated, then I would use static methods.
danpost danpost

2014/1/3

#
Affan wrote...
I have this code
if(getWorld() != null)
{
    if(canSee(Asteroid1.class))
    {
        if(Asteroid1.class != null)
        {
            Asteroid1.createExplosion();
            score = score+5;
            destroyMultiple(Asteroid1.class);
            createAsteroid1();
        }
    }
}
Line 5 will not perform like you want (the state of the condition is always the same). Line 7 is trying to run a method on a class and not on an object of that class. Look at the 'canSee' method and see what collision method is used there; use it again to get the particular asteroid that the shot hits. For example, if 'canSee' uses 'getOneIntersectingObject', then
if (canSee(Asteroid1.class))
{
    Asteroid1 asteroid = (Asteroid1) getOneIntersectingObject(Asteroid1.class);
    asteroid.createExplosion();
}
Line 3 gets the asteroid object that the 'canSee' method detected and line 4 runs the 'createExplosion' method on that object. This snippet could also be written as follows:
if (canSee(Asteroid1.class)) ((Asteroid1)getOneIntersectingObject(Asteroid1.class)).createExplosion();
Affan Affan

2014/1/3

#
Thanks Danpost and Schrucis. Fixed my problem completely
You need to login to post a reply.