Unity 3D Game Engine – Java Script – Polymorphism – Upcasting – Downcasting

Polymorphism – Upcasting – Downcasting vengono utilizzate per creare funzioni dinamiche tra classi legate da parentela padre-figlio.

Fruit Class


#pragma strict

public class Fruit 
{
    public function Fruit ()
    {
        Debug.Log("1st Fruit Constructor Called");
    }
    
    public function Chop ()
    {
        Debug.Log("The fruit has been chopped.");     
    }
    
    public function SayHello ()
    {
        Debug.Log("Hello, I am a fruit.");
    }
}

Apple Class


#pragma strict

public class Apple extends Fruit 
{
    public function Apple ()
    {
        Debug.Log("1st Apple Constructor Called");
    }
    
    //Apple has its own version of Chop() and SayHello(). 
    //When running the scripts, notice when Fruit's version
    //of these methods are called and when Apple's version
    //of these methods are called.
    //In this example, the "new" keyword is used to supress
    //warnings from Unity while not overriding the methods
    //in the Apple class.
    public function Chop ()
    {
        Debug.Log("The apple has been chopped.");     
    }
    
    public function SayHello ()
    {
        Debug.Log("Hello, I am an apple.");
    }
}

FruitSalad Class


#pragma strict

function Start () 
{
    //Notice here how the variable "myFruit" is of type
    //Fruit but is being assigned a reference to an Apple. This
    //works because of Polymorphism. Since an Apple is a Fruit,
    //this works just fine. While the Apple reference is stored
    //in a Fruit variable, it can only be used like a Fruit
    var myFruit = new Apple();

    myFruit.SayHello();
    myFruit.Chop();
    
    //This is called downcasting. The variable "myFruit" which is 
    //of type Fruit, actually contains a reference to an Apple. Therefore,
    //it can safely be turned back into an Apple variable. This allows
    //it to be used like an Apple, where before it could only be used
    //like a Fruit.
    var myApple = myFruit as Apple;
    
    myApple.SayHello();
    myApple.Chop(); 
}

Come funziona?

1. Fruit Class
– al suo interno ha i costruttori pubblici Fruit() – Chop() – SayHello()

2. Apple Class
– è una classe figlia di Fruit Class ‘… class Apple extends Fruit …’
– ha il proprio costruttore Chop() – SayHello()

3. FruitSalad Class
– la funzione Start() è la prima che si avvia al caricamento dello script
– richiama Apple().SayHello – Apple().Chop()
– fa il Downcasting a:


var myApple = myFruit as Apple;

quindi sarà richiamata Fruit().SayHello – Fruit().Chop()

Apple appartiene di sicuro alla categoria Fruit, ma non è detto che sia vero il contrario.