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

2011/12/13

New to this - non-static method cannot be referenced from static contex

sausagefingers sausagefingers

2011/12/13

#
Hi, So I am working through the Greenfoot book in Chapter 4. I want to make it so worm appear randomly. So I put the following code in the Worm class.
   public void act() 
    {
        makeRandomWorm();     
    } 
    public void makeRandomWorm(){
        int x = 0;
        if(x < 10)
        {
            CrabWorld.addObject(new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber(560));
        x = x + Greenfoot.getRandomNumber(600);
        }
    } 
However, I get the error - non-static method addObject cannot be referenced from static contex. I have searched this issue and from what I understand the addObject is an instance method and therefore cannot be called from a class. I considered moving it into the Crabworld class but as there is no act method I couldnt see how it would run. So I tried to create the worm first and then add it. but still no luck, any help would be appreciated.
    public void act() 
    {
        makeRandomWorm();
            
    } 
    
    public void makeRandomWorm(){
        int x = 0;
        if(x < 10)
        {
            Worm a = new Worm();
           Greenfoot.addObject(Worm a, 100, 100);
        x = x + Greenfoot.getRandomNumber(600);
        }
    } 
sausagefingers sausagefingers

2011/12/13

#
ah ha
    public void act() 
    {
        makeRandomWorm();
            
    } 
    
   public void makeRandomWorm(){
        int x = Greenfoot.getRandomNumber(1000);
        if(x < 1)
        {
            Worm worm = new Worm();
            getWorld().addObject(worm, Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber(560));
        }
    } 
          
}
getWorld() sorted it out. Can any one explain why though please?
mjrb4 mjrb4

2011/12/14

#
CrabWorld in this example is your class - you could create a thousand different CrabWorld objects as far as Java is concerned and that would be perfectly legitimate. A method like addObject() needs to be called on a specific instance of CrabWorld, which in this case is what getWorld() returns (the world that's currently active in the scenario.) If you call it on the CrabWorld class instead, the compiler has no way of knowing whether you want the method called on one world object, which world object, or whether you want it called on all the CrabWorld objects! From the compiler's perspective it doesn't make any sense.
You need to login to post a reply.