Back Up Next

Polimorfizem

polimorfizem.gif (7508 bytes)
Enemy a[ ]=new Enemy[4];
a[0]=new Alien( );
a[1]=new Monster( );
a[2]=new Vader( );
a[3]=new Enemy( );

a[0].move(); a[1].move(); a[2].move(); a[3].move( );
// vsakič se kliče druga (prava) funkcija!!!

Primer:

class Enemy      {
    int posX,posY;
    //--------------
    Enemy( ) {
        posX=posY=0;
    }
   //--------------
    Enemy(int x, int y) {
        posX=x; posY=y; 
    }
   //--------------
    void move(int x, int y) {
        posX += x; posY += y;
    }
   //--------------
    void printPosition( ) {        
        System.out.println("Genericen sovraznik na " + posX + " " + posY);
    }
}
//*****************************************************************
class Alien extends Enemy {
    Alien(int x, int y) {
        super(x,y);
    }
   //--------------
    void move(int x, int y) {
        posX *= x; posY *= y;
    }
   //--------------
    void printPosition( ) {        
        System.out.println("Alien na " + posX + " " + posY);
    }
   //---------------
}
//******************************************************************
class Monster extends Enemy {
    Monster(int x, int y) {
        super(x,y);
    }
   //----------------
    void printPosition() {        
        System.out.println("Monster na " + posX + " " + posY);
    }
   //--------------
}
//******************************************************************
class Vader extends Enemy {

    void printPosition() {        
        System.out.println("Darth Vader je povsod");
    }
   //--------------
}
//*****************************************************************
class Game
{
    public static void main(String argv[ ])   {

        Enemy a[ ]=new Enemy[4];
        a[0]=new Alien(1,1);
        a[1]=new Monster(2,3);
        a[2]=new Vader();
        a[3]=new Enemy(2,4);

        for (int i=0;i<4;i++) {
                a[i].move(1,2);
                a[i].printPosition();
        }
    }
}
Back Up Next