C# 繼承,構造函數的調用

先創建兩個類

class A
{
	public A()
	{
		Console.WriteLine("A empty param ctor");
	}
	public A(string s)
	{
		Console.WriteLine("A with string param ctor");
	}
	public void showA()
	{
		Console.WriteLine("showA");
	}
}

class B : A
{
	public B(string s)
	{
		Console.WriteLine("B with string param ctor");
	}
	public void showA()
	{
		Console.WriteLine("showB");
	}
}

實例化父類

  • 通過 new 父類來實例化
  • 通過 new 子類來實例化
    • 構造函數執行: 父類構造函數 -> 子類構造函數
    • 實例化出來的對象,只能執行父類方法,獲得父類屬性
class L_Base
{
	public void main()
	{
		A a = new B("s");
		a.showA();
	}
}
	
##輸出:
A with string param ctor
B with string param ctor
showA

實例化子類

  • 通過 new 子類來實例化
  • 構造函數執行順序:父類構造函數 -> 子類構造函數
  • 實例化對象,獲得父類和子類的所有方法和屬性, 如子類和父類有同名方法, 則執行子類方法
class L_Base
{
	public void main()
	{
		B b = new B("s");
		b.showA();
	}
}
##輸出:
A empty param ctor
B with string param ctor
showB

base 的使用

  • 實例化子類的時候,默認執行父類的無參構造函數
  • base 能執行調用父類對應的構造函數
  • 修改子類的構造函數
class B : A
{
	public B(string s): base(s)
	{
		Console.WriteLine("B with string param ctor");
	}
	public void showA()
	{
		Console.WriteLine("showB");
	}
}
##輸出:
A with string param ctor
B with string param ctor
showB
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章