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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值