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