(原創) derived-class要怎麼呼叫base-class的constructor? (.NET) (C#)
Abstract
有時我們在derived-class的constructor提供的參數,事實上是base-class的資料,或者base-class根本就是ABC(abstract base class),這時我們就得在derived-class的constructor去呼叫base-class的constructor。
Introduction
1/*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : Constructor_CallBaseConstructor.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo how to call base class constructor
7Release : 02/16/2007 1.0
8*/
9using System;
10
11namespace CSharpLab
12{
13 class Student {
14 public string name;
15
16 public Student(string name) {
17 this.name = name;
18 }
19 }
20
21 class Bachelor : Student {
22 public string lab;
23
24 public Bachelor(string name, string lab) : base(name) {
25 this.lab = lab;
26 }
27
28 public static void Main() {
29 Bachelor bachelor = new Bachelor("John", "PECLab");
30 Console.WriteLine(bachelor.name);
31 Console.WriteLine(bachelor.lab);
32 }
33 }
34}
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : Constructor_CallBaseConstructor.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo how to call base class constructor
7Release : 02/16/2007 1.0
8*/
9using System;
10
11namespace CSharpLab
12{
13 class Student {
14 public string name;
15
16 public Student(string name) {
17 this.name = name;
18 }
19 }
20
21 class Bachelor : Student {
22 public string lab;
23
24 public Bachelor(string name, string lab) : base(name) {
25 this.lab = lab;
26 }
27
28 public static void Main() {
29 Bachelor bachelor = new Bachelor("John", "PECLab");
30 Console.WriteLine(bachelor.name);
31 Console.WriteLine(bachelor.lab);
32 }
33 }
34}
執行結果
John
PECLab
PECLab
24行的constructor提供了兩個參數,name為base-class的資料,而lab為derived-class的資料,所以勢必呼叫base-class的constructor才行,C#的方式是在constructor initializer list使用base keyword,並帶入參數,這樣就可以執行base-class的constructor了。
C++是在constructor initializer list呼叫base-class的constructor,而Java是在body中使用super這個keyword。
See Also
(原創) derived-class要怎麼呼叫base-class的constructor? (C/C++)
(原創) derived-class要怎麼呼叫base-class的constructor?(Java)