
オーバーライド
Tutorial
intermediate
+0XP
5 mins
(12)
Unity Technologies

基底クラスのメンバーを子クラスのメンバーでオーバーライドする方法を学びます。
Languages available:
1. オーバーライド
Fruit クラスのコード
using UnityEngine;
using System.Collections;
public class Fruit
{
public Fruit ()
{
Debug.Log("1st Fruit Constructor Called");
}
// これらのメソッドは仮想メソッドであるため、子クラスでオーバーライドできます。
public virtual void Chop ()
{
Debug.Log("The fruit has been chopped.");
}
public virtual 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");
}
// これらのメソッドは override 指定がされているため、
// 親クラスの仮想メソッドをオーバーライドできます。
public override void Chop ()
{
base.Chop();
Debug.Log("The apple has been chopped.");
}
public override void SayHello ()
{
base.SayHello();
Debug.Log("Hello, I am an apple.");
}
}
FruitSalad クラスのコード
using UnityEngine;
using System.Collections;
public class FruitSalad : MonoBehaviour
{
void Start ()
{
Apple myApple = new Apple();
// Apple クラスのバージョンのメソッドが
// Fruit クラスのバージョンのメソッドをオーバーライドすることに注意してください。
// また、Apple クラスのバージョンは、Fruit クラスのバージョンを
// "base" キーワードを使って呼び出すため、両バージョンが呼び出されることにも注意してください。
myApple.SayHello();
myApple.Chop();
// オーバーライドは、ポリモーフィズムを使う状況でも役立ちます。
// Fruit クラスのメソッドは仮想メソッドで、
// Apple クラスのメソッドそれらをオーバーライドしているため
// Apple クラスのオブジェクトを Fruit クラスのオブジェクトにアップキャストする場合
// Apple クラスのバージョンのメソッドが使用されます。
Fruit myFruit = new Apple();
myFruit.SayHello();
myFruit.Chop();
}
}