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

2014/4/26

Can I have some help explaining this?

327458 327458

2014/4/26

#
Hello everyone, I recently found some code that helps me call a method from another class.
for (Object obj : getWorld().getObjects(Pins.class))  
    {  
        Pins pins = (Pins) obj;  
        pins.newRow();  
    }  
The class would be the Pins class, and every time this set of instructions were carried out, a new row of pins would be created. The code works perfectly, however I would like to understand why it works the way it is. I am not sure if I need a for loop at the top, but I am not sure what else will work. I need to add comments into my work for my school assessment, and to do that I need to understand why this code works.
danpost danpost

2014/4/26

#
Let us break it down: We are using a for loop to iterates through a collection of object. This collection is created by calling 'getWorld().getObjects(Pins.class)'. 'getWorld()' (Actor class method) returns the world that the actor, referred to by 'this', is in. 'getObjects' (World class method) returns a list of objects of the specified class (Pins.class) Each iteration will set 'obj' to a different Pins object that is in the world. The 'obj' variable holds a reference to an Object type object. '(Pins) obj' on line 3 casts the referenced object as a type of Pins object. It is then assigned to a variable, 'pins', that is to hold a Pins object. This 'typecasting' informs the compiler that the object is indeed of type Pins and it will now look in the Pins class for any fields or methods called on the object (which line 4 does). Line 4 calls 'newRow' (Pins class method) on the current Pins object being iterated on.
You need to login to post a reply.