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

2012/2/18

How can i call methods of other classes from a different class?

Sofalovesmusic Sofalovesmusic

2012/2/18

#
If i for example have the two calsses dog and cat and i am programming inside the class dog a method called bark and i want to write a method cat which (under a certain condition) makes the dog bark...how do i do that? (the methods are all working fine but i have no idea how to call that dog.bark(); from the cat) plus the actors are both in the world but not placed there by each other, but by the world...
danpost danpost

2012/2/18

#
You will need to get a reference to an instance of a dog object to call the method. If you are sure there will be an instance of a dog object in your world, use
1
2
Dog dog = getWorld().getObjects(Dog.class).get(0);
dog.bark();
If there is any chance there is not an instance of a dog object in your world, you will need to add
1
import java.util.List;
and then use
1
2
3
4
5
6
List<Dog> dogs = (List<Dog>)getWorld().getObjects(Dog.class);
if (!dogs.isEmpty())
{
    Dog dog = dogs.get(0);
    dog.bark();
}
Either way, make sure the method bark() in the Dog class has public access.
buckeye4life22 buckeye4life22

2014/2/3

#
What is that .get(0) thing? I get an error when I try to use it.
danpost danpost

2014/2/3

#
You should show how you are using it (with context code) and copy/paste the entire error message in your post. 'get(0)', or rather 'get(int)' is a List class method. Click on the link for more information on it. An alternate coding (without importing the 'List' class) is:
1
2
3
4
if (!getWorld().getObjects(Dog.class).isEmpty())
{
    ((Dog)getWorld().getObjects(Dog.class).get(0)).bark();
}
You need to login to post a reply.