派生クラスから基本クラスにアクセスするには「base」キーワードを使います。
以下の例では、基本クラスのコンストラクタとメソッドを呼び出しています。
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace ConsoleApplication1
{
class Pet
{
protected string _name;
protected bool _canFly;
public Pet(string name, bool canFly)
{
Console.WriteLine("class Pet のコンストラクタが呼ばれました。\n");
this._name = name;
this._canFly = canFly;
}
public string Name
{
get {return this._name;}
}
public bool CanFly
{
get {return this._canFly;}
}
public void Talk()
{
Console.WriteLine("私の名前は{0}です。", this._name);
Console.WriteLine("ちなみに私は空を{0}。", this._canFly ? "飛べます" : "飛べません");
}
}
class DogAsPet : Pet
{
protected Color _color;
public DogAsPet(string name, Color color) : base(name, false)
{
Console.WriteLine("class DogAsPet のコンストラクタが呼ばれました。\n");
this._color = color;
}
public Color Color
{
get {return this._color;}
}
public void Bark()
{
Console.WriteLine("ほえます。ワン!");
base.Talk();
Console.WriteLine("何か文句ある?");
}
}
class Program
{
static void Main(string[] args)
{
DogAsPet John = new DogAsPet("John", Color.Brown);
John.Bark();
}
}
}
上のプログラムを実行すると以下のような結果となります。
class Pet のコンストラクタが呼ばれました。
class DogAsPet のコンストラクタが呼ばれました。
ほえます。ワン!
私の名前はJohnです。
ちなみに私は空を飛べません。
何か文句ある?