public class ClassSample
{
// メンバー変数
public int x;
public int y;
// コンストラクター(クラス名と同じ名前のメソッド)
public ClassSample() {
// メンバー変数の初期値を設定
this.x = 10;
this.y = 20;
}
}
class Program
{
static void Main(string[] args)
{
ClassSample c = new ClassSample(); // ここでコンストラクターが呼ばれる
}
}
パラメータをもつコンストラクター
コンストラクターに引数(パラメーター)を指定できます。
public class ClassSample
{
// メンバー変数
public int x;
public int y;
// コンストラクター
public ClassSample(int x, int y) {
// メンバー変数の初期値を設定
this.x = x;
this.y = y;
}
}
class Program
{
static void Main(string[] args)
{
// ↓ここでコンストラクターが呼ばれる
ClassSample c = new ClassSample(10, 20);
}
}
new ClassSample(10, 20); newを使う際のクラス名の後ろにパラメータを指定します。
パラメータあり、なし両方でコンストラクターを書いて状況で使い分けたりします。
public class ClassSample
{
// メンバー変数
public int x;
public int y;
// コンストラクター1
public ClassSample() {
this.x = 10;
this.y = 20;
}
// コンストラクター2
public ClassSample(int x) {
this.x = x;
}
// コンストラクター3
public ClassSample(int x, int y) {
this.x = x;
this.y = y;
}
}
class Program
{
static void Main(string[] args)
{
ClassSample c1 = new ClassSample(); //コンストラクタ1が呼ばれる
ClassSample c2 = new ClassSample(10); //コンストラクタ2が呼ばれる
ClassSample c3 = new ClassSample(10, 20); //コンストラクタ3が呼ばれる
}
}