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

2014/10/27

Checking whether an object is of a specific class

classicjimmy classicjimmy

2014/10/27

#
Say you have an object of class Bird and you want to find an intersecting object of class Sky. One way to find that object is to write:
public Sky intersectingSky()
{

   for (Sky s: getWorld().getObjects(Sky.class))
   {
        if (s ==getOneIntersectingObject(Sky.class))
      {
          return s; 
      }
   }
return null;
}
But does there not exist an easier way to do this, without having to go through all Sky objects? .
classicjimmy classicjimmy

2014/10/27

#
Never mind, I found out myself:
public Sky intersectingSky()
{
Object o = getOneIntersectingObject(Sky.class); 
Sky s = (Sky)o; 
        if (s != null)
        {            
            return s;   
        }
        
return null;
        
    }
danpost danpost

2014/10/27

#
Or, more simply:
public Sky intersectingSky()
{
    return (Sky)getOneIntersectingObject(Sky.class);
}
This method, unless called from a different class or called several times, would be a bit wasteful as the code '(Sky)getOneIntersectingObject(Sky.class)' could replace the call to the method 'intersectingSky()' without making it to difficult to follow.
classicjimmy classicjimmy

2014/10/27

#
Thanks, that's really simple and beautiful.
You need to login to post a reply.