使用 new 關鍵字建立一個對象時,"runtime"必須使用那個類的定義來構造對象,"runtime"必須從作業系統申請一個記憶體區域,在其中填充由類定義的字段,然後調用一個構造器執行必須的任何初始化工作。
構造器(constructor)是一種特殊方法(method),它在建立類的一個執行個體時自動運作。它與類(class)同名,能擷取參數,但不能傳回任何值(即使是 void)。
每個類都至少要一個構造器。如果不提供自己的構造器,編譯器會幫你自動生成一個預設構造器。但是編譯器生成的預設構造器不做任何實際的事情。預設構造器非常好寫,隻需添加一個與類同名的 public 方法,不讓它傳回任何值就可以了。
若省略 public 關鍵字,構造器将預設為 private(這和其他任何方法和字段是一樣的)。private 構造器不能再類的外部建立對象。
下面建立一個 student 類,裡面有預設構造器。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AreaClass
{
class Program
{
static void Main(string[] args)
{
Student student1;
student1 = new Student(); // 調用預設構造器
Console.WriteLine("name is {0}", student1.name);
// name 定義為 public 類型,可以在類 Student 外部通路
//Console.WriteLine("age is {0}", student1.age);
// age 定義為 private 類型,不能再類 Student 外部通路
student1.Score(90); // 方法自己傳遞實參
}
}
class Student
{
private int age;
public string name = "Steven";
public Student() // 預設構造器
{
}
public void Score(int score)
{
Console.WriteLine("{0}'s score is {1}", name, score);
}
}
}
運作後結果如下圖所示:
下面建立一個 Circle 類,裡面有預設構造器和重載的構造器。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AreaClass
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("預設構造器:");
Circle c;
c = new Circle(); // 調用預設的構造器
Console.WriteLine("Area = {0}", c.Area());
Console.WriteLine("a = {0}", c.a); // c.a = 10
Console.WriteLine("static b = {0}", Circle.b); // static c.b = 1
Console.WriteLine("c = {0}", c.c); // c.c = 1
//Console.WriteLine(c.radius); // radius 在 Circle 類内部定義時
// 是 private 類型,是以不能在外部通路
Console.WriteLine();
Console.WriteLine("重載的構造器:");
Circle d;
d = new Circle(9); // 調用重載的構造器,此處用構造器給方法傳遞參數
Console.WriteLine("Area = {0}", d.Area());
Console.WriteLine("static b = {0}", Circle.b); // static b.b = 2
Console.WriteLine("c = {0}", d.c); // b.c = 1
Console.WriteLine();
}
}
class Circle
{
private int radius;
public int a = 10;
public static int b = 0; // b 為 static 變量,可以被各個對象共享。
// 具體就是每次調用 b 都會+1
public int c = 0; // c 為非 static 變量,不能被各個對象共享。
// 具體就是每個對象調用的是"單獨"的 c
public Circle() // 預設構造器
{
radius = 0;
b++;
c++;
}
public Circle(int intiaRadius) // 重載的構造器
{
radius = intiaRadius;
b++;
c++;
}
public double Area()
{
return Math.PI * radius * radius; // private 類型的 radius 值能在類内部通路
}
}
}
運作後結果如下圖所示: