ポリモーフィズム

Tutorial

intermediate

+0XP

5 mins

(18)

Unity Technologies

ポリモーフィズム

ポリモーフィズム、アップキャスティング、およびダウンキャスティングを使用して、継承されたクラス間に強力で動的な機能を作成する方法を学びます。

Languages available:

1. ポリモーフィズム

Fruit クラスのコード

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 クラスのコード

using UnityEngine;
using System.Collections;

public class Apple : Fruit 
{
    public Apple()
    {
        Debug.Log("1st Apple Constructor Called");
    }

    // Apple には、独自のバージョンの Chop() と SayHello() があります。
    // スクリプトを実行するとき、これらのメソッドの Fruit クラスのバージョン
    // および、これらのメソッドの Apple クラスのバージョンが
    // それぞれ呼び出されるタイミングに注意してください。
    // この例では、"new" キーワードは、Apple クラスで
    // メソッドをオーバーライドしていないときに Unity が出す
    // 警告を抑制するために使用されます。
    public new void Chop()
    {
        Debug.Log("The apple has been chopped.");        
    }

    public new void SayHello()
    {
        Debug.Log("Hello, I am an apple.");
    }
}

FruitSalad クラスのコード

using UnityEngine;
using System.Collections;

public class FruitSalad : MonoBehaviour
{
    void Start () 
    {
        // ここで、変数 "myFruit" の型は Fruit なのに
        // Apple クラスのオブジェクトへの参照が割り当てられていることに注目してください。
        // このコードはポリモーフィズムがあるので機能します。
        // リンゴは果物だから、これは問題ないというわけです。
        // Apple クラスの参照が Fruit 型の変数に保存されていますが
        // この場合は Fruit 型の変数としてのみ使用できます。
        Fruit myFruit = new Apple();

        myFruit.SayHello();
        myFruit.Chop();

        // これはダウンキャスティングと呼ばれます。
        // Fruit 型の変数 "myFruit" には、実際には Apple への参照が格納されています。
        // したがって、安全に Apple 型の変数に戻すことができます。
        // これにより、Apple 型の変数として使用できます。
        // この処理を行う前は、Fruit 型の変数としてしか使用できなかったことに注意してください。
        Apple myApple = (Apple)myFruit;

        myApple.SayHello();
        myApple.Chop();    
    }
}

Complete this Tutorial