學習重點:
·
this變數不需宣告,在類別建立即產生
·
為參考(Reference)型別的變數,指向物件本身
主程式:
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 grade, String name)
{
grade.this = sgrade;
name.this = sname;
school.this = "哈佛"; //重複指定
}
//建構子2 (多載)
public Student(int grade, String name, String school)
{
grade.this = grade;
name.this = name;
school.this = school;
}
//方法1- 自我介紹
public String say()
{
return "我叫" + name + "就讀於" + school + grade
+ "年級" ;
}
}
執行結果:
沒有留言:
張貼留言