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

2015/1/10

Non-Static Method ??

elementa elementa

2015/1/10

#
Hi! So for my Greenfoot game I have two doors: a correct door and a wrong door, and these are both in separate classes. When the correct door is clicked, I would like to be able to switch that image as well as switching the image from the wrong door class. I have created a method in the wrong door class which switches its image, and have called the class by "WrongDoor.switchtoSecond()"
 public void firstCAnswer()
    {
        if (Greenfoot.mouseClicked(this))
        {
            setImage(new GreenfootImage("3-correct.png"));
           [b]secondCAnswer();[/b]
            WrongDoor.switchtoSecond();
        }  
    }
However, when compiled, the bolded line of code says "non-static method switchtoSecond() cannot be referenced from a static context" How would I be able to fix this?
elementa elementa

2015/1/10

#
Sorry I "bolded" the wrong line! I meant this line:
WrongDoor.switchtoSecond();
danpost danpost

2015/1/10

#
Using a simple analogy: a factory creates cars and a car is something that moves; you would not then say 'factory, move'. Now, a class is like a factory and it creates objects like your doors which you decided to give the ability for them to change images; you would not then say 'class, change image' -- you would say 'door, change image. 'WrongDoor' is the name of your class, not the name of any object it creates. Now, you do not actually have to name your object; since it is the only WrongDoor object in the world, you can use '(WrongDoor)getWorld().getObjects(WrongDoor.class).get(0)' to get a reference to it. 'getObjects(WrongDoor.class)' returns a list of all WrongDoor objects in the world; 'get(0)' returns the first (and only, in this case) element from the list, which is a WrongDoor object, but it was only returned as an Object object. We know that it is indeed a WrongDoor object and can inform the compiler that it is by the typecasting '(WrongDoor)'. Now, we can call the 'switchtoSecond' method on the object that is now known to be a WrongDoor object (the compiler would not have looked in the WrongDoor class for the 'switchtoSecond' method had we not typecasted the reference as a WrongDoor object):
((WrongDoor)getWorld().getObjects(WrongDoor.class).get(0)).switchtoSecond();
elementa elementa

2015/1/11

#
Oh, I understand ! Thank you so much!
You need to login to post a reply.