學習重點:
主程式:
- 建構子(Constructor)無輸出型別
- 建構子的名稱需與class的名稱相同
- 多載(Overloaded): 允許相同建構子擁有不同的引數個數
主程式:
private
void
button1_Click(object sender, EventArgs
e)
{
Student s1 = new Student(6, "小王"); // 建立物件s1
Student s2 = new Student(3, "小三"); // 建立物件s2
Student s3 = new Student(5, "小三", "MIT"); //
建立物件s3
MessageBox.Show(s1.say());
MessageBox.Show(s2.say());
MessageBox.Show(s3.say());
}
Student 類別 :
class Student
{
//屬性
public int grade;
public String name;
public String school;
//建構子1
public Student(int sgrade, String sname)
{
grade =
sgrade;
name =
sname;
school
= "哈佛"; //重複指定
}
//建構子2 (多載)
public Student(int sgrade, String sname, String sschool)
{
grade =
sgrade;
name =
sname;
school
= sschool;
}
//方法1- 自我介紹
public String say()
{
return "我叫" + name + "就讀於" + school + grade
+ "年級" ;
}
}
執行結果:
沒有留言:
張貼留言