構造方法的作用
構造方法的主要作用就是為類中的成員變量進行初始化。
<!--構造的注意事項 -->
1、構造方法名必須和類名相同。
2、構造方法能夠添加參數。
3、構造方法可以進行重載,系統根據參數不同選擇調用符合的構造方法。
4、構造方法可以不寫,系統會添加一個默認的無參構造方法。
5、構造方法可以是私有的,私有后不允許通過該構造方法初始化對象。
6、構造方法會在創建對象或者第一次訪問靜態成員的時候調用。
系統默認的構造:
public class student { //系統默認生成的構造方法
public student() { } }
通過構造方法初始化成員變量:
首先定義幾個屬性,例如:
public string name;//姓名
public string sex;//性別
public int age;//年齡
public int height;//身高
public int weight;//體重
public string beizhu;//備注
構造方法的參數可以是所有屬性參數,也可以是其中幾個,比如:這是一個帶有所有屬性參數的構造方法
public student(string name, string sex, int age, int height, int weight) { this.name = name; this.sex = sex; this.age = age; this.height = height; this.weight = weight;
this.beizhu = "使用的是第一個構造方法(全部參數)";
}
這是一個只有兩個屬性參數的構造方法
public student(string name,string sex) { this.name = name; this.sex = sex;
this.beizhu = "使用的是第二個構造方法(部分參數)"; }
以上代碼寫在student類中,那么怎樣在別的類中調用呢,如下代碼寫在Main方法里:
//這是主方法
class Demo { static void Main(string[] args) { student stu = new student("王明", "男", 18, 180, 90); Console.WriteLine(stu.name + stu.beizhu); student stu2 = new student("李華", "女"); Console.WriteLine(stu2.name + stu2.beizhu); } }
stu和stu2都是student的實例化,但是參數不同,所以對應的是兩個不同的構造方法,看輸出結果:
那如果你不寫構造方法呢,該怎么調用方法里邊的屬性呢
那就需要這樣
static void Main(string[] args) { //student stu = new student("王明", "男", 18, 180, 90); //Console.WriteLine(stu.name + stu.beizhu); //student stu2 = new student("李華", "男"); //Console.WriteLine(stu2.name + stu2.beizhu);
student stu = new student(); stu.name = "星籟歌姬"; stu.sex = "男"; stu.age = 19; stu.height = 185; stu.weight = 120; }
一條一條的給方法的屬性賦值,灰常的不夠銀杏,灰常的麻煩,所以構造方法還是更方便一點
原創內容轉載請注明:https://www.cnblogs.com/ccgn/articles/16149719.html