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

2012/7/18

Polymorphism in greenfoot?

davemib123 davemib123

2012/7/18

#
Hi All, having trouble understanding the term polymorphism. could some one give a simple scenario example?
davmac davmac

2012/7/18

#
Nearly all Greenfoot scenarios are an example of polymorphism! Every time you have an Actor subclass which implements the 'act()' method, you have polymorphism - seeing as the new act() method overrides the method from the base class (which is Actor). If you have a variable containing a reference to an Actor instance, and you call the act() method on it, then it dispatches the appropriate act() method according to the actual type of the object.
davemib123 davemib123

2012/7/18

#
Would this be correct: If a mover class is created with the method moveLeft.
int velocity;    
public void moveLeft()
    {
        setLocation ( getX() - velocity, getY() );
    }
The hero subclass then uses:
public class hero extends mover
{
    public hero()
    {
        this.velocity = 4;
    }
    public void act() 
    {
        moveLeft();
    }    
}
The enemy subclass then can use the left command with a different velocity value Is that polymorphism or am I on the wrong lines?
davmac davmac

2012/7/18

#
That's about it. Actually the enemy could do something completely different in the act method, and it will still be an example of polymorphism. (But, by convention, class names should start with a capital - Hero and Mover rather than hero and mover).
davemib123 davemib123

2012/7/18

#
great ... thanks for the syntax tip davmac
You need to login to post a reply.