Il termine polimorfismo indica la possibilità di definire metodi e proprietà con lo stesso nome, in modo che, ad esempio, una classe derivata possa ridefinire un metodo della classe base con lo stesso nome.
Create an empty object and attach the scripts:
Console:
– FruitSalad.cs
using UnityEngine;
using System.Collections;
public class FruitSalad : MonoBehaviour
{
void 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
Fruit 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.
Apple myApple = (Apple)myFruit;
myApple.SayHello();
myApple.Chop();
}
}
– Fruit.cs
using UnityEngine;
using System.Collections;
public class Fruit
{
public Fruit()
{
Debug.Log("1st Fruit Constructor Called");
}
public void Chop()
{
Debug.Log("The fruit has been chopped.");
}
public void SayHello()
{
Debug.Log("Hello, I am a fruit.");
}
}
– Apple.cs
using UnityEngine;
using System.Collections;
public class Apple : Fruit
{
public 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 new void Chop()
{
Debug.Log("The apple has been chopped.");
}
public new void SayHello()
{
Debug.Log("Hello, I am an apple.");
}
}
– 1st Fruit Constructor Called
– 1st Apple Constructor Called
– Hello, I am a fruit
– The fruit has been chopped
– Hello, I am an apple
– The apple has been chopped
For italian people, come funziona?
1. Polimorfismo: Apple viene memorizzata in Fruit
Fruit myFruit = new Apple(); Crea un’istanza della classe Apple(), si attiva il costruttore senza parametri della classe padre -> public Fruit() e della classe figlia -> public Apple()
2.
myFruit.SayHello();
-> Hello, I am a fruit
myFruit.Chop(); -> The fruit has been chopped
3. Downcasting: Apple dentro a MyFruit torna ad essere Apple
Apple myApple = (Apple)myFruit;
myApple.SayHello();
-> Hello, I am an apple
myApple.Chop(); -> The apple has been chopped
Un esempio game:
– Polimorfismo: ‘Goblin’ memorizzato in ‘Nemici’
– Downcasting: Goblin in Nemici torna Goblin